Reputation: 5378
(function() {
f();
f = function() {
console.log(8);
}
})()
function f() {
console.log(9)
}
f();
prints 9, 8.
Why isn't it 8, 9?
Why doesn't the anonymous function execute first?
Upvotes: 1
Views: 181
Reputation: 1776
If you need the output you can modify it like this
(function() {
f();
function f() {
console.log(8);
}
})()
function f() {
console.log(9)
}
f();
But let me explains why it executes that way.
(function() {
f(); // Line Number -a
f = function() { //b
console.log(8);
}
})()
function f() { //c
console.log(9)
}
f() //d
There is the difference.The line 'b'
is a function expression.It is only defined when it is reached.So when it reaches 'a'
i doesn't actually know about the 'b' function.On the contrary, c
is a function declaration and when it encouters 'f()' it immediately knows.
Right after 'a'
is executed (which executes 'c'
,it will be modified by 'b'
to its new defanition.
To make it more clear consider this function
function printMe(){
var a;
console.log(a);
a = 10;//It an expression
}
The output you would get is it is defined.Because untill that line a=10
is not executed, it doesn't have a value.
There is this little code written by Philip Roberts which actually shows how your code is being executed .Please have a look here
Upvotes: 1
Reputation: 131466
Because you defined f()
after the invocation of it.
So it doesn't invoke the f()
function defined in the IIFE but the outter f() :
by reversing the order :
(function () {
f = function () {
console.log(8);
}
f();
})()
you could have 8 and 8 as output as in both cases it invokes the overridden f()
function.
Upvotes: 1
Reputation: 386730
Please see the numbers for order of execution.
Basically you have 4 parts,
The function declaration with a hoisted function,
an IIFE calling the function
a new assignment of f
and
the last call of the new function.
(function() {
f(); // calling hoisted function 2
f = function() { // assigning new function to f 3
console.log(8);
}
})()
function f() { // hoisted function 1
console.log(9)
}
f(); // calling new function 4
Upvotes: 4