I was seeing some Javascript code and I stumbled upon something like this:
function() {
if(true) {
var a = 5;
}
alert(a);
}
I was pretty sure this would output undefined but it didn't ? Can someone tell me why?
I was seeing some Javascript code and I stumbled upon something like this:
function() {
if(true) {
var a = 5;
}
alert(a);
}
I was pretty sure this would output undefined but it didn't ? Can someone tell me why?
Share Improve this question asked Jun 5, 2014 at 15:42 John DohertyJohn Doherty 1575 bronze badges 7 | Show 2 more comments4 Answers
Reset to default 14JavaScript has function level scope, not block level scope.
The var
statement is hoisted so your code is equivalent to:
function() {
var a;
if(true) {
a = 5;
}
alert(a);
}
If JavaScript had block level scope, then it still wouldn't output undefined
. Since a
would be undeclared in the alert
statement, you would trigger a reference error.
The reason this works is a result of what is called hoisting. Hoisting moves the declaration of the variable to the top of the scope. So your function really looks like this:
function() {
var a;
if(true) {
a = 5;
}
alert(a);
}
"Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behaviour is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code." - var MDN
Variable definitions are moved to the top of the function (variable hoisting); there are no block level variables.
The compiler changes your code to
function() {
var a;
if(true) {
a = 5;
}
alert(a);
}
JS doesn't have block scopes just function\global scopes.
In your case the var is declared with no value at the top of the function and then is assigned.
Here's a good tutorial on scopes.
if
block anyway... – War10ck Commented Jun 5, 2014 at 15:45