A function can be defined by declaration or an expression.
In the previous tutorial, you have learned the syntax of function declarations:
The function will not be executed immediately after the declaration, it will be called when we need it.
Function expressions can be stored in variables:
After a function expression is stored in a variable, the variable can also be used as a function:
The above function is actually a anonymous function (the function has no name).
Functions are stored in variables and do not require a function name. They are usually called by a variable name.
Note: The above function ends with a semicolon because it is an execute statement.
The Function() Constructor
In the example above, we learned that functions are defined by the keyword function .
In fact, you don't have to use a constructor. The above example can be written as:
We already learned about "hoisting" in previous tutorials.
Hoisting applies to variable declarations and function declarations.
Thus, functions can be called before they are declared:
There is no promotion when defining functions using expressions.
Function expressions can be "self-calling".
Self-invoking expressions are called automatically.
If the expression is immediately followed by (), it will be called automatically.
Declared functions cannot be called by themselves.
It is a function expression by adding parentheses:
The above function is actually an anonymous self-calling function (no function name).
Functions Can Be Used as Values
Functions are Objects
arguments.length property returns the number of parameters received during the function call:
The toString () method returns the function as a string:
Note: Functions are defined as attributes of objects and are called object methods. If a function is used to create a new object, it is called the object's constructor.