This is an example of js elevation
See that the function declaration has a code
if(condition){
function sayHi(){
alert('hi')
}
}else{
function sayHi(){
alert('Yo')
}
}
It is said that this code has invalid syntax. Most browsers will return the second statement, and Firefox will return the first statement. Why is this?
If it is changed to function expression form, why is this?
var sayHi;
if(condition){
sayHi=function(){
alert('Hi')
}
}else{
sayHi=function(){
alert('Yo!')
}
}
Because the first one is a function declaration, but functions are generally not declared in if-else
The second one is to assign the anonymous function to the variable. There is no such thing as promotion
Writing function xxx(){} directly will result in early declaration. If there are two such functions with the same name, it is equivalent to executing var xxx twice at the top, so it is invalid
It has nothing to do with declaration prefix. At that time, the JavaScript specifications were still ES5, browsers had not yet implemented block-level scope (ES2016+), and the scope level was only the function level. So you wrote it
and written by
No essential difference
js is declared in advance! ! ! The function will be directly mentioned at the top of the scope when it is declared. There is no scope in if, so the two functions are one scope, and the second one will replace the first one. ! As for your second code, you declare the variable sayhi first, and then assign the value to sayhi after the if judgment,