The js parser does not treat function declarations and function expressions equally. For function declaration, the js parser reads the statements first to ensure that the declaration has been parsed before all code is executed, and the function expression is like defining other basic types of variables, it will be parsed only when a sentence is executed. so far, we have not made any difference between the function declaration and the function expression. In fact, when the parser loads data to the execution environment, the function declaration and function expression are not treated equally. The parser will first read the function declaration and make it available (accessible) before executing any code. As for the function expression, it must wait until the parser executes to its line of code, to be interpreted and executed. Example:
The code is as follows:
Alert (sum (10, 10 ));
Function sum (num1, num2)
{
Return num1 + num2;
}
The above code can be correctly executed, because before the code starts to be executed, the parser has passed a process called function declaration hoisting, read and add the function declaration to the execution environment. When you evaluate the code, the JavaScript engine declares the functions for the first time and places them on the top of the source code tree. Therefore, even if the declared function code is behind the code that calls it, the JavaScript engine can also promote the function declaration to the top. If the above function declaration is changed to an equivalent function expression as shown in the following example, an error occurs during execution.
The code is as follows:
Alert (sum (10, 10 ));
Var sum = function (num1, num2)
{
Return num1 + num2;
};
The above code will cause an error during running because the function is located in an initialization statement rather than a function declaration. In other words, no reference to the function is saved in the sum variable before the statement where the function is executed, because the first line of code will cause the "unexpected identifier" (unexpected identifier) error, it will not actually be executed to the next line.
In addition to the differences that can be accessed through variables during declaration, the syntax of function declaration and function expression is actually equivalent.
Note: You can also call the function declaration and function expression at the same time, for example, var sum = function sum (){}. However, this syntax may cause errors in Safari.
The above is all the content of this article. I hope it will be helpful for you to learn javascript.