So far, we have not distinguished between function declarations and function expressions. In fact, the parser does not treat function declarations and function expressions equally when loading data into the execution environment. The parser takes the lead in reading the function declaration and making it available (accessible) before executing any code, and the function expression must wait until the parser executes to the line of code it is in before it is actually interpreted. The following example:
Copy Code code as follows:
Alert (sum (10,10));
function sum (num1,num2)
{
return num1+num2;
}
The above code can be executed correctly, because before the code starts executing, the parser has read and added the function declaration to the execution environment through a procedure named function declaration hoisting. When the code is evaluated, the JavaScript engine declares the functions for the first time and places them at the top of the source tree. So, even if the code that declares the function is behind the code that calls it, the JavaScript engine can also elevate the function declaration to the top. If you change the above function declaration to an equivalent function expression, as shown in the following example, an error occurs at execution time.
Copy Code code as follows:
Alert (sum (10,10));
var sum=function (num1,num2)
{
return num1+num2;
};
The above code will have an error at run time because the function is in an initialization statement, not a function declaration. In other words, a reference to a function is not saved in the sum of variables until the statement in which the function is executed, and because the first line of code causes a "unexpected identifier" (unexpected identifier) error, it is not actually executed to the next line.
In addition to the difference between a declaration and a variable access function, the syntax of a function declaration and a function expression is actually equivalent.
Note: You can also call function declarations and function expressions, such as Var sum=function sum () {}. However, this syntax can cause errors in Safari.
The above is the entire content of this article, I hope to learn JavaScript can help you.