I am learning javascript and can someone please explain the following code snippet for me?
var state=true;
function bob(){ var state=false; }
bob()
What should be the state value and why?
Many thanks,
L
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
At the end of execution,
statewill betrue, because the functionbob()defines a local variable namedstateinstead of assigning to the global variable of the same name. However, in the following example,statewould be false:By omitting the
varkeyword, the JavaScript engine will travel up the scope chain looking for a variable namedstate, until it finds one or reaches the global scope. This can be further demonstrated with nested functions: