It should print undefined.
This is because of hoisting which happens to variable a. In case of declaring a variable with var keyword, the variable is hoisted to the current execution context, which for a is the enclosing function.
Undefined
Due to variable hoisting within function scope.
Well it appears to be "hoisted" because there are two phases that happens during compilation, in which during the first phase, the function and variable declaration, including the variables within function, happens;
And during the second (execution) phase, the assignment happens.
Since var is function scoped, whenever any var variable is encountered within a function, it gets declared during the first phase. This also explains why the var is accessible outside a block scope like if-else blocks within a function.
So at the end of first phase, the code will seem to be like below:
function printVariable() {
var a;
console.log(a);
var a = 15;
}
And a non-assigned variable is assigned undefined as value by default.
Please feel free to correct me if I am wrong with my explanation
Top comments (5)
It should print
undefined
.This is because of hoisting which happens to variable
a
. In case of declaring a variable withvar
keyword, the variable is hoisted to the current execution context, which fora
is the enclosing function.Undefined
Due to variable hoisting within function scope.
Well it appears to be "hoisted" because there are two phases that happens during compilation, in which during the first phase, the function and variable declaration, including the variables within function, happens;
And during the second (execution) phase, the assignment happens.
Since var is function scoped, whenever any var variable is encountered within a function, it gets declared during the first phase. This also explains why the var is accessible outside a block scope like if-else blocks within a function.
So at the end of first phase, the code will seem to be like below:
function printVariable() {
var a;
console.log(a);
var a = 15;
}
And a non-assigned variable is assigned undefined as value by default.
Please feel free to correct me if I am wrong with my explanation
Very beautifully explained with in-deph details. Good job
"this is a variable"
No, its undefined. Please check Sriram explanation.