0

What will be the output of the following code and why?

author
subina kallyani
medium
3
35
var a = 3;
(function() {
console.log(a);
var a = 5;
})();
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