Let’s say here is a sample code snippet and we are required to tell the possible output for this snippet and provide an explanation for it
var name = 'Zakir'; (() => { name = 'Rahul'; return; console.log(name); function name(){ let lastName = 'Singh'; } })(); console.log(name);
Let’s go through this problem line by line with a naive approach
1 → ‘Zakir’ stored in variable name
3 → We enter inside a self-executing anonymous function
4 → The variable name is reinitialized to ‘Rahul’
5 → return statement is encountered, so we exit the function
15 → print the name variable to screen whose current value is ‘Rahul’
So, the final output will be
Rahul
But, unfortunately, it’s wrong, let’s go through the code once again to see where we went wrong, this time keeping the concept of variable and function hoisting in mind.
1 → ‘Zakir’ stored in variable name
3 → We enter inside a self-executing anonymous function
As we enter the function, function hoisting takes on and the function name() which is defined at the bottom of the self-executing function is hoisted to very top of the self-executing function And at that intermediate state the code would be something like −
Example
let name = 'Zakir'; (() => { let name; name = 'Rahul'; return; console.log(name); name = function(){ let lastName = 'Singh'; } })(); console.log(name);
Note that whenever a variable/function is hoisted to the top of its scope it’s only defined and initialised, it is initialised at its actual position, at the top it is undefined, but it exists.
So, when the variable name is reinitialised it’s the local variable name which gets reinitialized and not the global variable so, after this we return out of the self-executing function and print the global variable name to the console, which still holds ‘Zakir’. Therefore, the output will be −
Output
Zakir