2
var salary = "1000$";

(function () {
    console.log("Original salary was " + salary); //1000$

    salary = "5000$";

    console.log("My New Salary " + salary); //5000$
})();

(function () {
    console.log("Original salary was " + salary); //undefined ?? 

    var salary = "5000$";

    console.log("My New Salary " + salary); //5000$
})();

Why and how first and third console logs are displaying different outputs ?

AKS
  • 51
  • 5
  • Hint: Not different than if the function was regularly declared and invoked… – Bergi Jun 28 '16 at 12:00

2 Answers2

2

This is due to variable hosting .In your second IIFE function , you have already declared salary variable , it actually moves to the top of the function and overshadows your global salary function

javascript convrts this code like .see the code.

  var salary = "1000$";

    (function () {
        console.log("Original salary was " + salary); //1000$

        salary = "5000$";

        console.log("My New Salary " + salary); //5000$
    })();

    (function () {
        var salary ;
        console.log("Original salary was " + salary); //undefined ?? 

        // get move to opvar salary = "5000$";

       salary = "5000$";

        console.log("My New Salary " + salary); //5000$
    })();
Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
1

The top line creates a global variable called salary. Within the scope of the second function, there is a local variable called salary. This means in the second function you cannot access the global variable in that way, and the local variable hasn't been set yet so it is actually undefined until the line where it is set.

Andrew
  • 1,963
  • 3
  • 25
  • 35