As of the official release of ES2017 spec (2017-07-08), EcmaScript does support true block scope now using the let
or const
keywords.
Since ECMAscript doesn't have block scope but function scope, its a very good idea to declare any variable on the top of your function contexts.
Even though you can make variable and function declarations at any point within a function context, it's very confusing and brings some weird headaches if you aren't fully aware of the consequences.
Headache example:
var foo = 10;
function myfunc() {
if (foo > 0) {
var foo = 0;
alert('foo was greater than 0');
} else {
alert('wut?');
}
}
Guess what, we're getting a 'wut?' alert when calling myfunc
here. That is because an ECMAscript interpreter will hoist any var
statement and function declaration to the top of the context automatically. Basically, foo
gets initialized to undefined
before the first if statement
.
Further reading: JavaScript Scoping and Hoisting