function declaration
The function foo will be hoist (promoted) before the entire program executes, so it is available in the entire scope (scope) that defines the Foo function. It is fine even if you call it before the function definition.
Foo (); Works because Foo is created before this code runs
function foo () {}
Because I'm going to write an article about scopes, so here's a few details.
function expression
For function declarations, the name of a function is required and optional for a function expression, so there is an anonymous function expression and a named function expression. As follows:
function declaration: Functions functionname () {}
Function declared: function functionname[Optional] () {}
So I knew that if there was no function name, it would be a function expression, but what about the case of a function name?
Javascript states 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 an expression:
Let's give a few extreme examples of expressions:
!function foo () {}
true && function foo () {}
The above statements are just here to differentiate between function expressions, which are generally not written in this way. Then use a contrasting example to see the effect:
Foo1 ();//foo1 is isn't defined
foo2 ()//works because Foo2 was created before this code runs!function foo1
() {
Alert (' foo1 works ');
function Foo2 () {
alert (' Foo2 works ');
An anonymous function expression
var foo = function () {};
The example above assigns an anonymous function to the variable foo.
Foo ' Undefined '
foo ();//This raises a typeerror
var foo = function () {};
Because Var is a declaration, the variable foo is hoist (promoted) here, so the variable foo is callable when the program executes.
However, the value of the variable foo is undefined because the assignment statement takes effect only at run time.
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 invoked inside the bar function. This is because Javascript has a mechanism for handling named functions, and the name of a function is always valid within the scope of the function.