search

Home  >  Q&A  >  body text

javascript - I see a function in the function declaration section and I don’t quite understand it.

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!')
    }
}
我想大声告诉你我想大声告诉你2732 days ago812

reply all(4)I'll reply

  • 黄舟

    黄舟2017-07-05 10:40:34

    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

    reply
    0
  • 黄舟

    黄舟2017-07-05 10:40:34

    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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-07-05 10:40:34

    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

    if(condition){
        function sayHi(){
            alert('hi')
        }
    }else{
        function sayHi(){
            alert('Yo')
        }
    }

    and written by

    function sayHi(){
      alert('hi')
    }
    function sayHi(){
      alert('Yo')
    }

    No essential difference

    reply
    0
  • PHP中文网

    PHP中文网2017-07-05 10:40:34

    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,

    reply
    0
  • Cancelreply