function declarations and expressions
A function is a first-class object in JavaScript, which means that the function can be passed like any other value.
A common use is to pass anonymous functions as callback functions to asynchronous functions.
function declaration
function foo () {}
The above method is parsed (hoisted) before execution, so it exists anywhere in the current context,
It is true even if it is invoked above the function definition body.
Foo (); Normal operation because Foo was created before code was run
function foo () {}
function Assignment Expression
var foo = function () {};
This example assigns an anonymous function to the variable foo.
Foo ' Undefined '
Foo (); Error: TypeError
var foo = function () {};
Because VAR defines a declaration statement, the parsing of the variable foo is before the code is run, so the Foo variable is already defined when the code is run.
However, because the assignment statement executes only at run time, the value of Foo defaults to undefined before the corresponding code executes.
An assignment expression for a named function
Another special case is assigning a named function to a variable.
var foo = function bar () {
Bar (); Normal operation
}
Bar (); Error: Referenceerror
is not visible outside of the bar function declaration, because we have already assigned the function to Foo;
However, it is still visible inside the bar. This is due to the naming process of JavaScript, where function names are always visible within a function.