There are mainly three ways to define a function, function declaration, function expression, and the new Function
constructor. Function declaration and function expression are the more commonly used methods, while the constructor way can be used to define a function from a string.
Function declaration hoists both the declaration and assignment, which means the entire function body is hoisted to the top of the scope.
This means that a function defined within a certain scope can be called from any position within that scope, and the entire function body will be hoisted. However, there are exceptions:
Here, we can see that the function declaration is hoisted, but the function body is not. JavaScript only has function scope, global scope, and the block scope introduced in ES6
with let
and const
. In this case, there is no issue with the if
scope, as it's within the same scope. However, since the interpreter cannot determine the content inside the if
during the preprocessing, it only hoists the function declaration variable and does not assign the function body.
Function expression only hoists the variable declaration, essentially hoisting the variable and assigning an anonymous function object to it.
From this, we can see that there is a priority relationship between directly declaring a function and declaring a function through function expression.
In JavaScript, functions are first-class citizens. In the book "You Don't Know JavaScript" (Volume I), on page 40, it is mentioned that functions are hoisted first, and then variables. This means that within the same scope, functions are hoisted first. Thus, the execution priority in JavaScript is function declaration, variable declaration, and variable assignment.
The new Function
way can parse a string into a function.
new Function
differs from eval
in its determination of the execution environment for the parsed content.