Just now,I saw some code like this:
if(condition){
var xx='sss';
}
//do something
if(condition){
console.info(xx);
}
Now, I just wonder why the second if statement work? How can it access the xx variable since it is a local variable defined in another if statement?
varin JavaScript is scoped to the containing execution context (e.g., the whole function’s scope, or the whole global scope if thevaris at global scope), not the block. JavaScript doesn’t (yet) have block scope (ECMAScript6 looks likely to add it, via the newletkeyword).The code you’ve quoted is exactly equivalent to this:
This is covered by Section 10.5 of the specification, which describes what the engine does when entering a new execution context. (It’s basically a two-phase process, first setting up all the declarations, and then executing step-by-step code.)
More: Poor misunderstood
var