In the following example, why does the second f() prints 2.
I was thinking it would print 3 since the function prints in the same context where it is called.
(function() {
f();
f = function() {
console.log(2);
}
}());
function f() {
console.log(3);
}
f();
When function f() is hoisted, but f = function() is not hoisted, this results in following order:
// hoisted
function f()
{
console.log(3);
}
(function () {
f(); // uses definition with 3
// overwrites f
f = function()
{
console.log(2);
}
}());
f(); // uses overwritten f with 2
Here is the execution order.
function f() hoisted
IIFE executes and creates a global object called f
The second step overshadows the hoisted function due to its name and due to the fact that is being declared as a global variable
If you put var or let before the function expression Inside the IIFE and move the function call below the expression, the second call would have printed 3.
(function() {
var f = function() {
console.log(2);
}
f();
}());
function f() {
console.log(3);
}
f();