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' ?
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' ?
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 x
declared 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:
function foo(a) {
if (a) {
var b = "something";
}
console.log(b);
}
Variable b
is local to that function, hence whatever the value of a
, usage of b
won't accidentally refer to a variable declared on an enclosing scope.
Note: javascript only has function level scoping, it has no block level scoping.