Is defining JavaScript variables inside if-statements correct?
if(a==1){
var b = 1;
} else {
var b = 0;
}
I know the code above will work, however, WebMatrix highlights the variables.
Should I define the variables outside the if-statement? Or the first option’s correct? Or it doesn’t really matter?
var b = '';
if(a==1){
b = 1;
} else {
b = 0;
}
As of the official release of ES2017 spec (2017-07-08), EcmaScript does support true block scope now using the
letorconstkeywords.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:
Guess what, we’re getting a ‘wut?’ alert when calling
myfunchere. That is because an ECMAscript interpreter will hoist anyvarstatement and function declaration to the top of the context automatically. Basically,foogets initialized toundefinedbefore the firstif statement.Further reading: JavaScript Scoping and Hoisting