Reputation: 2023
Why the second console.log()
gives 2
, insted of 1
?
function f() {
console.log(2);
}
f();
(function() {
f();
f = function() {
console.log(1);
}
})();
Upvotes: 0
Views: 70
Reputation: 15481
That is because the function declaration is getting executed twice.
FYI - function declaration gets hoisted but function expression does not.
function f() { // function declaration
console.log(2);
}
f(); // 2
(function() {
f(); // 2
f = function() { // function expression
console.log(1);
}
// you can use function expression here now that it is defined
f(); // 1
})();
// will output:
// 2
// 2
// 1
Read up:
Upvotes: 0
Reputation: 2672
The second "console.log(1)" outputs 2 because it is really the first "console.log(2)" that you are calling — twice. You never actually called the function that would trigger "console.log(1)". Here's a more representative example of what is happening:
function f(value) {
console.log(value);
}
f('a');
(function() {
f('b');
f = function() {
console.log('c');
}
// unless you call "f()" at this point, this would not work. The "f = func ... " doesn't get hoisted.
})();
Notice how the output is "a" and "b", but "c" is never logged. Variable assignments of functions don't get hoisted, I'm assuming that you would thought would happen?
Hope that helps.
Upvotes: 1
Reputation: 92440
In javascript function declarations are hoisted within enclosing scopes, but assignments are not. What you have in your second call is not a function declaration — you are just changing the value of an existing variable. If you wanted a hoisted version of f()
in your second call you would need to do something like:
function f() {
console.log(2);
}
f();
(function() {
f();
function f() {
// this is a function declaration so it will be hoisted to the top
console.log(1);
}
})();
Upvotes: 3
Reputation: 101
You are calling f(); in the IIFE before your function expression. If you move your second f(); call below the expression you will get the result you are expecting.
function f() {
console.log(2);
}
f();
(function() {
f = function() {
console.log(1);
}
f();
})();
Upvotes: 1