Consider the following two JavaScript snippets:
var x = 2;
function f() {
var y = x;
eval('var x;');
return y;
}
vs.
var x = 2;
function f() {
var y = x;
var x;
return y;
}
The only difference is I’ve replaced eval('var x;'); with var x;.
The first one returns 2, but the second one returns undefined. Why?
Variable declarations are hoisted by the parser to the top of the lexical scope. In the second block of code, the way it’s actually run is:
Function declarations are also hoisted. The net effect is that a variable declaration should be considered to always include the entire lexical scope in which it appears. If variable
xis declared withvaranywhere in a function, then every reference toxin that function is to the local variable.In your first example, the
eval()line is just a regular expression statement, so it’s executed in order of its appearance in the function.