简体   繁体   中英

Why javascript doesn't look up global scope in second case

foo will lookup b value with 2 as expected when executing in console

function foo() {
    console.log(b)
}
var b = 2
foo() // 2 for console.log

but when I do this

function foo() {
    console.log(b)
    var b = 2
    console.log(b)
}
var b = 2
foo() // undefined for first console.log

it won't lookup b in global scope anymore why ?

It is because of what is called Javascript Hoisting, this is how javascript sees your code:

function foo() {
  var b; // javascript hoisted this variable on top
  console.log(b) // so here you see underfined
  b = 2;
  console.log(b);
}

Now because javascript hoised variable b on top of function, your global variable b was never used and hence statement immendiately after hoisted variable showed undefined . So if you remove new declaration ( var keyword) from your function, you should still have access to global b variable.

BTW, it is good practice to declare all your variables on top of function like:

function foo() {
  var b = 2;
  console.log(b);
}

To know more on the topic, see this:

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