I have this example code:
var salary = "1000$";
(function () {
console.log("Original salary was " + salary);
var salary = "5000$";
console.log("My New Salary " + salary);
})();
I found out that the first console.log will print undefined as the salary value.
and the second console.log will print 5000$ as the salary.
So, by executing this code, I understand that immediately invoked function get invoked in the first stage of javascript compilation when function and variables are put in variable object inside execution context. Am I right?
First stage is hoisting variables. Second stage is execution.
Self-executing functions are executed on the second stage, just as any other piece of code. Your second salary is overwriting the upper declaration. In fact, you can ignore the first completely. After the first phase, the variable is hoisted and the code looks like this:
var salary;
console.log("Original salary was " + salary);
salary = "5000$";
console.log("My New Salary " + salary);
If you want to catch yourself from introducing this bug into your code you should use let and const instead, as these are not hoisted. You should also be using a linter that will catch these issues.
Mayank Chandola
salary variable inside the IIFE will be hoisted so it's value will be
undefinedat the firstconsole.logFor simplicity you can run this in your console.
var a=5; function x() { console.log(a); var a=3; } x();