-1

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.

HK boy
  • 1,398
  • 11
  • 17
  • 25
subbu swaroop
  • 11
  • 1
  • 5

1 Answers1

3

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()
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73