var foo = 'hello';
var myfunc = function() {
console.log(foo);
var foo = foo || 'world';
console.log(foo);
}
myfunc();
why is the first foo logged to be ‘undefined’ ?
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.
Because on which line you actually declare a variable using “var” is irrelevant, as long as it remains in the same function. If a function has a
var xdeclared anywhere within it, then any reference to that name is considered local to the scope where it is declared.Of course, normally you don’t reference a variable before it’s declared, but consider this snippet:
Variable
bis local to that function, hence whatever the value ofa, usage ofbwon’t accidentally refer to a variable declared on an enclosing scope.Note: javascript only has function level scoping, it has no block level scoping.