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?
JavaScript is a dynamic language, that isn't always picky about things like variable scoping. So, this "feature" allows you to write the code
I would recommend avoiding this, since it makes your program harder to understanda and reason about.
var
in JavaScript is scoped to the containing execution context (e.g., the whole function's scope, or the whole global scope if thevar
is at global scope), not the block. JavaScript doesn't (yet) have block scope (ECMAScript6 looks likely to add it, via the newlet
keyword).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
If you declare a variable using var within a function, the variable is scoped to within that function. An if statement is not a function.
I'm assuming in this case both if statements are within the same function and therefore xx is in scope?
var
declarations affect the entire scope of the smallest containing function or program. JavaScript is not block scoped.Crock says:
Note, this is changing with the
let
statement, and in current JavaScript (EcmaScript 5), the variable name in acatch
block is block scoped.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.
for that matter you can take it to extremes:
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 scopehope this helps -ck
useful link: http://www.youtube.com/watch?v=taaEzHI9xyY&feature=youtu.be#t=42m57s
javascript doesn't have block scope, so
var xx='sss'
is either locally scoped (if your sample code is inside a function) or globally scoped (if your sample code is not contained in a function).