Why does this return 2 instead of 1? Seems the second "var" is silently ignored.
function foo()
{
var local = 1;
{
var local = 2;
}
return local;
}
foo()
/*
2
*/
Why does this return 2 instead of 1? Seems the second "var" is silently ignored.
function foo()
{
var local = 1;
{
var local = 2;
}
return local;
}
foo()
/*
2
*/
In javascript there is only function level scope and global scope. you cannot create a block scope and it adds no special meaning and does not create any scope.
And this is how your code ends up
function foo()
{
var local = 1;
local = 2;
return local;
}
foo();
In ES6 you can create block level scopes with the help of Let. ES6 is not supported yet. more on that here
From the MDN :
The scope of a variable in JavaScript is the whole function in which it is declared (or the global scope), so you only have one variable
local
here.Your code is equivalent to
Note that ES6 (the new norm of JavaScript) does introduce a lexical scoping with
let
but it's not yet really available.