Function declaration
function foo() {}The function foo will be hoisted before the entire program is executed, so it is available in the entire scope (scope) that defines the foo function. Even calling it before the function definition is OK.
foo(); // Works because foo was created before this code runsfunction foo() {}Because I plan to write an article specifically introducing scope, I won't explain it in detail here.
Function expressions
For function declarations, the name of the function is necessary, but for function expressions, it is optional. Therefore, anonymous function expressions and named function expressions 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 should we judge if there is a function name?
Javascript specifies that if the entire function body is part of an expression, then it is a function expression, otherwise it is a function declaration. The following is the expression:
var fuc = foo(){}Let's give a few more extreme expression examples:
!function foo(){}true && function foo(){}The above statements are just to distinguish function expressions, and they are generally not written like this. Then 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 expressions
var foo = function() {};The above example assigns an anonymous function to the variable foo.
foo; // 'undefined'foo(); // this raises a TypeErrorvar foo = function() {};Since var is a declaration, the variable foo is hoisted (promoted) here, so when the program is executed, the variable foo is callable.
However, since the assignment statement only takes effect at runtime, the value of the variable foo is undefined.
Named function expressions
Another thing to talk about is the assignment of named functions.
var foo = function bar() { bar(); // Works};bar(); // ReferenceErrorHere, the named function bar is assigned to the variable foo, so it is invisible outside the function declaration, but it can still be called inside the bar function. This is because Javascript's mechanism for naming functions, the name of the function is always valid in the scope inside the function.