简体   繁体   中英

javascript variable access mystery

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM