Home  >  Q&A  >  body text

javascript - Js function declaration and function expression

`alert(sum(10,10));
var sum=function(num1,num2){

   return num1+num2;

};`
Why is the error reported? Isn’t there a variable promotion?

世界只因有你世界只因有你2663 days ago857

reply all(4)I'll reply

  • phpcn_u1582

    phpcn_u15822017-07-05 10:57:27

    When we write js code, we have two ways of writing, one is function expression, and the other is function declaration.
    What we need to focus on is:

    Only function declaration forms can be promoted.

    1. Function declaration form [Success]

    function myTest(){ 
        foo(); 
        function foo(){ 
            alert("我来自 foo"); 
        } 
    } 
    myTest();
    

    2. Function expression method [Failure]

    function myTest(){ 
        foo(); 
        var foo =function foo(){     // 看这里
            alert("我来自 foo"); 
        } 
    } 
    myTest();
    

    Read my article: http://www.jianshu.com/p/85a2...

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-07-05 10:57:27

    Function expressions are not hoisted.

    Read "Javascript Advanced Programming" again.

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-07-05 10:57:27

    Declaration and expression are different. If you declare, not only the definition will be done in advance, but the assignment will also be done in advance, but the expression will not. For example:

    a();
    function a(){}; //等同于
    var a = function(){};
    a();
    ///////对于表达式有
    a();
    var a = function(){}; //等同于
    var a;
    a();
    a = function(){}; //简单来讲就是表达式的赋值必须要等程序运行到相关行的时候才会进行

    reply
    0
  • ringa_lee

    ringa_lee2017-07-05 10:57:27

    Same as above, your function creation method is in function literal form, change it to

    alert(sum(10,10));
    function sum(num1,num2){
        return num1+num2;
    }

    That’s it

    reply
    0
  • Cancelreply