Function is the First Class Object in Javascript, which means the function can be passed like other values. One of the most common usage is to pass an anonymous function as a callback function to another asynchronous function. Function Declaration
function foo() {}
Function foo will be promoted by hoist before execution of the entire program, so it is available in the entire scope (scope) that defines the foo function. It is okay to call the function even before it is defined.
foo(); // Works because foo was created before this code runsfunction foo() {}
Because I want to write an article about the scope, I will not detail it here.
Function expression
For function declaration, the function name is required, and for function expressions, it is optional. Therefore, an anonymous function expression and a naming function expression appear. As follows:
Function declaration: function functionName (){}
Function declaration: function functionName [Optional] () {}
Then I know that if there is no function name, it must be a function expression. But how can I determine if there is a function name?
Javascript requires that if the entire function body is part of an expression, it is a function expression, otherwise it is a function declaration. The following is an expression:
var fuc = foo(){}
Let's take a few extreme expressions as an example:
!function foo(){}true && function foo(){}
The preceding statement is only used to differentiate function expressions. It is generally not written in this way. Let's use a comparison example to see the effect:
foo1();//foo1 is not defined foo2();//works because foo2 was created before this code runs!function foo1() { alert('foo1 works');};function foo2() { alert('foo2 works');};
Anonymous function expression
var foo = function() {};
In the above example, an anonymous function is assigned to the variable foo.
foo; // 'undefined'foo(); // this raises a TypeErrorvar foo = function() {};
As var is a declaration, the variable foo is hoist (promoted) Here. Therefore, when the program is executed, the variable foo is callable.
However, since the value assignment statement takes effect only at run time, the value of the variable foo is undefined.
Name function expression
Another thing to talk about is the assignment of naming functions.
var foo = function bar() { bar(); // Works};bar(); // ReferenceError
Here, the name function bar is assigned to the variable foo, so it is invisible outside the function declaration, but can still be called within the bar function. This is because Javascript handles the naming function, and the function name is always valid in the function's internal scope.