var a = 3;
(function() {
console.log(a);
var a = 5;
})();
0
What will be the output of the following code and why?
subina kallyani
medium
3completed
35
Answer
The output will be: undefined
This behavior happens because of variable hoisting in JavaScript.
The code is interpreted as:
(function() {
var a;
console.log(a); // undefined
a = 5;
})();At the time of console.log(a), a is declared but not yet assigned, so it outputs undefined.
Important Note:
If var a inside the function was removed, it would print 3, as it would refer to the outer a variable.
Click to Reveal Answer
Tap anywhere to see the solution
Revealed
Comments0