Home > Article > Web Front-end > Javascript Study Notes: Functions (1): Function Declaration and Function Expression_Basic Knowledge
Function declaration
function foo() {}
Function foo will be hoisted before the entire program is executed, so it is available in the entire scope where foo function is defined. There is no problem even if it is called before the function is defined.
foo(); // Works because foo was created before this code runs function foo() {}
Because I plan to write a special article introducing scope, I won’t go into details here.
Function expression
For function declarations, the name of the function is required, 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 to judge the case where there is a function name?
Javascript stipulates 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 statement is only to distinguish function expressions, and is generally not written like this. Then use a comparative 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() {};
The above example assigns an anonymous function to variable foo.
foo; // 'undefined' foo(); // this raises a TypeError var foo = function() {};
Since var is a declaration, the variable foo is hoisted here, so when the program is executed, the variable foo is callable.
But since the assignment statement only takes effect at runtime, the value of variable foo is undefined.
Named function expression
Another thing to talk about is the assignment of named functions.
var foo = function bar() { bar(); // Works }; bar(); // ReferenceError
Here, the named function bar is assigned to the variable foo, so it is not visible outside the function declaration, but can still be called inside the bar function. This is because of the way Javascript handles named functions. The name of a function is always valid in the scope inside the function.