The following code:
function a() {
console.log('1')
}
(function() {
console.log(a);
if(1) {
function a() {
console.log('2');
}
}
})()
After running, the output is undefined.
After removing the if condition, the output is the second a function
function a() {
console.log('1')
}
(function() {
console.log(a);
// if(1) {
function a() {
console.log(2);
}
// }
})()
Knowing that the function has been promoted, in the second piece of code, the second a function will be promoted to before the console.log(a) code, so the second a function is run and output.
But in the first piece of code, I don’t understand why undefined is output.
Conditional function declarations are processed in the same way as function expressions. Therefore, conditional function declarations lose the hoisting properties of function declarations.
Reference URL: /q/10...
When using the function keyword in an if else statement to declare a function, the promotion of variables is different in different browsers. It's just that the declaration of a variable is promoted here, and if else is removed, it becomes a pure function scope.
In your IIFE
is a function expression, not a function declaration. When the if is removed, it is a function declaration. If is not removed, conosle.log(a), a represents the undefined variable a, refer to https://developer.mozilla.org. ..