There are two common ways to define functions:
1. function declaration
2. Function expressions
# differences
(1) function declaration, which has the feature of function declaration promotion.
(2) The Name property of the function declaration function is the names of the functions; functions defined with function expressions in ES5, the Name property is an empty string, and the name of the function in ES6.
# function Declaration Promotion
function declaration
1 SayHello (); // calling a function before the function declaration does not cause an error because the function declaration is promoted. 2function SayHello () {3 console.log ("hello!"); // hello! 4 Console.log (Sayhello.name); // SayHello 5 }
function expression
1 SayHello (); // Typeerror:sayhello is not a function uses the method of a function expression to define functions, and calling a function before a variable declares a function will cause an error. 2 var SayHello = function () { 3 Console.log ("hello!"); // hello! 4 console.log (sayhello.name); // sayhello. Note: In ES5, the Name property of the anonymous function is an empty string (P176), which returns the original name of the named function in ES6. 5 } 6 SayHello (); //
# Note the following situation
1 //don't do that. Because of the reason for the function declaration promotion, the following code is invalid in ECMAScript, and the browser tries to fix the error in an inconsistent manner. P1762 varFlag =true;3 if(flag) {4 functionSayhi () {5Console.log ("Hi");6 }7}Else{8 functionSayhi () {9Console.log ("Yo");Ten } One } ASayhi ();//Strict mode will error. Referenceerror:sayhi is not defined
1 //You can do this by using a function expression. 2 varFlag =true;3 varSayhi;4 if(flag) {5Sayhi =function(){6Console.log ("Hi");7 }8}Else{9Sayhi =function(){TenConsole.log ("Yo"); One } A } -Sayhi ();
JS Elevation 7. Function Expressions (1)