Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this work in javascript?

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?

like image 881
hguser Avatar asked Dec 10 '22 02:12

hguser


2 Answers

var in JavaScript is scoped to the containing execution context (e.g., the whole function's scope, or the whole global scope if the var is at global scope), not the block. JavaScript doesn't (yet) have block scope (ECMAScript6 looks likely to add it, via the new let keyword).

The code you've quoted is exactly equivalent to this:

var xx;   
if(condition){
    xx='sss';   
}
//do something

if(condition){
    console.info(xx);
}

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

like image 160
T.J. Crowder Avatar answered Dec 11 '22 14:12

T.J. Crowder


In JavaScript the scope is exacted to the closure (the last enclosing function block, or defaults to the window object). When a variable is declared anywhere within that function block it is hoisted to the top of the scope, so in essence a variable exists as undefined starting at the very top of the scope if it is declared anywhere in the scope.

Think of it like this, when the code begins executing it scans all the instructions for declarations and allocates the symbol name starting immediately.

console.log(x);  // undefined
console.log(y);  // error: Uncaught ReferenceError: y is not defined
var x;

for that matter you can take it to extremes:

console.log(x);  // undefined, not an error

while (false) {
  if (false) {
    var x;
  }
}

even though var x can't possibly be reached, and during execution would be optimized away completely. the engine will still hoist the variable to the top of the scope

hope this helps -ck

useful link: http://www.youtube.com/watch?v=taaEzHI9xyY&feature=youtu.be#t=42m57s

like image 26
ckozl Avatar answered Dec 11 '22 16:12

ckozl