Home >Web Front-end >JS Tutorial >Function declaration and function expression in JavaScript

Function declaration and function expression in JavaScript

PHPz
PHPzOriginal
2016-05-16 15:57:031394browse

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 will first read the function declaration and make it available (accessible) before executing any code; as for the function expression, it will not be actually interpreted and executed until the parser reaches the line of code where it is located. The following example:

The code is 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 Function declarations have been read and added to the execution environment through a process called function declaration hoisting. When evaluating code, the JavaScript engine declares functions on the first pass 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 hoist the function declaration to the top. If, as shown in the following example, the above function declaration is changed to an equivalent function expression, an error will occur 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 when running because the function is located in an initialization statement , rather than a function declaration. In other words, the variable sum will not hold a reference to the function until the statement in which the function is executed; moreover, since the first line of code will cause an "unexpected identifier" error, it actually does not Will not execute to the next line.

Except for the fact that the function can be accessed through variables during declaration, the syntax of function declaration and function expression are actually equivalent. of.

Note: You can also call function declaration and function expression at the same time, such as var sum=function sum(){}. However, this syntax will cause errors in Safari.

The above is the entire content of this article. I hope it will be helpful to everyone learning javascript.

For more related tutorials, please visit javascript tutorial

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn