Home > Article > Web Front-end > What is the difference between function declaration and function expression?
There are two ways to define functions: function declaration and function expression.
The syntax of function declaration is like this:
function functionName(arg0,arg1){//函数体}
First is the function keyword, then the name of the function. These are the two ways to specify the function name. Regarding function declaration, one of its most important features is function declaration promotion, which means that the function declaration will be read before executing the code. This means that you can place the function declaration after the statement that calls it. For example:
a();function a(){alert("a");}//a
This example will not go wrong because the function declaration will be read before executing the code.
The second way to create a function is a function expression. The following is the most common way:
var a = function(arg0,arg1){//函数体};
This form looks like a regular variable assignment statement, that is, create a function and put It is assigned to the variable a. The function created in this case is called an anonymous function because there is no identifier after the function keyword.
Function expressions, like other expressions, must be assigned a value before use. The following code will cause an error:
a();var a = function(){alert("a");};//错误//补充说明:使用该方法定义函数,只有变量声明提前了,变量初始化代码仍在原来的位置
1. The function name in the function declaration is required, but it is optional in the function expression. .
//函数声明 function sum(a, b) { return a + b; } alert(sum(1, 2));
//函数表达式 /* var s = function sum(a, b) { return a + b; } alert(s(1, 2)); */ var s = function(a, b) { return a + b; } alert(s(1, 2)); //以上两种都可以
2. Functions defined with function declarations can be called before the function declaration, while functions defined with function expressions can only be called after the declaration.
The fundamental reason is that the order in which the parser reads these two definitions is different: the parser will read the function declaration, that is, the function declaration can be called at any position; and for function expressions, The parser will only start execution when it reads the line where the function expression is located (see Part 1, "How Functions are Defined" for details).
The above is the detailed content of What is the difference between function declaration and function expression?. For more information, please follow other related articles on the PHP Chinese website!