In JavaScript, functions are defined in two ways, function definition expressions and function declarations, as shown in the following examples:
var test = function (x) {
return x;
}
function test (x) {
return x;
}
Although function definition expressions and Function declaration statements contain the same function names, and both create new function objects, there is a difference between the two.
The function name in a function declaration statement is a variable name, and the variable points to the function object.
The function definition expression and the variable declared through Var, its function is advanced to the top of the script or function, so it is visible within the entire script and/or function. In this case, only the function variable declaration is in advance, and the initialization code of the function is still in its original position. But with a function declaration, the function name and function body are advanced, that is, functions and functions nested within the script are declared before the other code in the current context, or it can be called before a function is declared.
As an example:
Test (1);
function test (x) {
Console.log (x);
}
The above code executes normally and the result output is 1, because the function name and function body are declared in advance for the function declaration statement, which can be called before the declaration.
Test (1);
var test = function (x) {
Console.log (x);
}
The above code does not execute properly and will error.
Because for function definition expressions, only the function variable declaration is in advance, but the initialization code of the function is still in its original position, which is equivalent to the following code
var test; function variable declaration in advance
Test (1);
var test = function (x) {
Console.log (x);
}
Therefore, the error test is not a function.
[]javascript function defines the difference between an expression and a function declaration