I recently came across this javascript code in a competitive site and couldn't understand how this pretty much works.
var a= 1;
(function(){
console.log(a);
var a = 2;
console.log(a);
})();
I expected the output to be..
1 2
But to my surprise, the original output was..
undefined 2
Can someone please explain how it works? Thanks in advance.
The declaration of variable a
is brought to the top of the scope. This process is called hoisting.
var a= 1;
(function(){
var a;
console.log(a);
a = 2;
console.log(a);
})();
Consider a general snippet without a IIFE and global variable.
function func(){
console.log(x)
var x = 2;
console.log(x)
}
func()
The declaration of x
is hoisted to the top of the scope of the function.So the above code is same as
function func(){
var x; //x is declared and its value is undefined
console.log(x)
x = 2;
console.log(x)
}
func()