4 ms·
Paste this into your browser location bar (it won't navigate away): javascript:void(function(){a = 1; {var a = 2;} alert(a)}()) That var a doesn't declare
by jerf 14y ago
Paste this into your browser location bar (it won't navigate away):
javascript:void(function(){a = 1; {var a = 2;} alert(a)}())
That var a doesn't declare a new var within its scope, it declares it in the function, plus it is counterintuitive how that var a "retroactively" makes that local scope. Javascript has lexical scoping, but only within functions, not within all the scopes other languages have.
- secoif 14y agoYou want block scoping. Block scoping is coming in ES6 with the let keyword.
- klibertp 14y agoPython is the same here, for example, any many other languages too. Making `a` a local variable here is rather ugly thing to do, but it's (somewhat) consistent with how `function` keyword (not an expression) works. The point being: JS implements full and proper lexical scoping; implementing lexical scoping for every block is not a requirement for having lexical scoping.