JavaScript function definition method: function expressions and function declarations. This article explores when to use function expressions, when to use function declarations, and explains the differences between the two.
Frequency declarations have been widely used for a long time, but function expressions have gradually dominated. Many developers are unsure when to use which one, which ultimately leads to the wrong choice.
There are some key differences between function expressions and function declarations. Let's take a closer look at these differences and when to use function expressions and function declarations in your code.
function funcDeclaration() { return '函数声明'; } let funcExpression = function () { return '函数表达式'; }
Function declaration is performed when a function is created and named. After writing the function
keyword, follow the function name and declare the name of the function. For example:
function myFunction() { // 执行某些操作 };
As you can see, declare the function name (myFunction
) when creating the function. This means you can call it before defining the function.
This is an example of a function declaration:
function add(a, b) { return a + b; };
Function expressions are performed when creating a function and assigning it to a variable. The function is anonymous, which means it has no name. For example:
let myFunction = function() { // 执行某些操作 };
As you can see, the function is assigned to the myFunction
variable. This means you have to define it before calling the function.
This is an example of a function expression:
let add = function (a, b) { return a + b; };
There are some key differences between function expressions and function declarations:
Similar to let
statements, function declarations are promoted to the top of other codes.
Function expressions will not be promoted. This allows them to retain copies of local variables taken from the scope in which they are defined.
Usually, you can use function declarations and function expressions interchangeably. However, sometimes function expressions lead to easier-to-understand code without the need for temporary function names.
So, when should function expressions be used and when should function declarations be used?
The answer depends on your needs. If you need a more flexible function or a function that won't be promoted, function expressions are the best choice. If you need a more readable and understandable function, use the function declaration.
As you can see, the two syntaxes are similar. The most obvious difference is that function expressions are anonymous, while function declarations are famous.
Nowadays, when you need to do something that a function expression cannot do, function declarations are usually used. If you don't need to perform operations that can only be performed with a function declaration, it's usually better to use function expressions.
Use function declaration when you need to create a recursive function or need to call a function before defining it. As a rule of thumb, when you don't need to do both, use function expressions to write cleaner code.
There are some key advantages to using function declarations.
Function expressions also have some advantages.
In most cases, it is easy to determine which method to define a function is best for your needs. These guidelines will help you make decisions quickly in most cases.
Use function declarations in the following cases:
Use function expressions in the following cases:
That is, in many cases, the flexibility of function expressions becomes a powerful advantage.
There are many ways to function expressions be more useful than function declarations.
Closures can be used when you want to pass parameters to a function before executing it. A good example of how this benefits you is when looping through the NodeList .
Closure allows you to retain additional information, such as indexes, when the information is unavailable after the function is executed.
function funcDeclaration() { return '函数声明'; } let funcExpression = function () { return '函数表达式'; }
The additional event handler is executed later (after the loop ends), so the closure is required to preserve the appropriate value of the for
loop.
function myFunction() { // 执行某些操作 };
It is easier to understand why the problem occurs by extracting the for
function from the doSomething()
loop.
function add(a, b) { return a + b; };
The solution here is to pass the index as a function parameter to the external function so that it can pass the value to the internal function. You will usually see the information you need to use handler functions to organize internal return functions.
let myFunction = function() { // 执行某些操作 };
Learn more about closing packages and their usage.
Function expressions can be passed directly to the function without the need to assign values to intermediate temporary variables.
You see them most often in the form of anonymous functions. Here is a familiar example of jQuery function expression:
let add = function (a, b) { return a + b; };
Function expressions are also used to process array items when using methods such as forEach()
.
They also don't have to be unnamed anonymous functions. It is best to name function expressions to help express what functions should do and help debug:
function tabsHandler(index) { return function tabClickEvent(evt) { // 对选项卡执行操作。 // 可以从此处访问 index 变量。 }; } let tabs = document.querySelectorAll('.tab'), i; for (i = 0; i < tabs.length; i += 1) { tabs[i].onclick = tabsHandler(i); }
IIFE helps prevent your functions and variables from affecting the global scope.
All properties in it are within the scope of anonymous functions. This is a common pattern to prevent unexpected or undesirable side effects from code elsewhere.
It is also used as a module mode to include code blocks in easily maintained sections. We explore these more in-depth in Uncovering the Mystery of JavaScript Closures, Callbacks, and IIFE.
This is a simple example of IIFE:
function funcDeclaration() { return '函数声明'; } let funcExpression = function () { return '函数表达式'; }
… When used as a module, the code can be easily maintained.
function myFunction() { // 执行某些操作 };
As we can see, function expressions are not fundamentally different from function declarations, but they can often produce cleaner, more readable code.
They are widely used, making them an essential part of every developer toolbox. Are you using function expressions in your code in any interesting way that I didn't mention above? Please let me know in the comments!
The main difference between function expressions and function declarations is the way the JavaScript engine interprets them. Function declarations are parsed before any code is executed, which means you can call functions declared later in your code. This is called function lifting. On the other hand, function expressions are not promoted and therefore cannot be called before definition.
Of course, here is an example of each:
Function declaration:
function add(a, b) { return a + b; };
Function expression:
let myFunction = function() { // 执行某些操作 };
When you need to create functions that will be used throughout your code, function declarations are usually used because they are promoted to the top of the scope. This means you can call the function before declaring it in your code. Function expressions, on the other hand, are usually used for functions that require only one or a finite number of times, or when a function is passed as an argument to another function.
Yes, function expressions can be named. This is very useful for debugging, because the name of the function will appear in the stack trace. Here is an example:
let add = function (a, b) { return a + b; };
Function promotion in JavaScript is a behavior in which a function declaration is moved to the top of its containing scope during the compilation phase (before the code is executed). This means you can call the function before declaring it in your code. However, it should be noted that function expressions (even expressions assigned to variables) will not be promoted.
Call the function expression immediately (IIFE) is a function expression that is executed immediately after its definition. The syntax of IIFE is as follows:
function tabsHandler(index) { return function tabClickEvent(evt) { // 对选项卡执行操作。 // 可以从此处访问 index 变量。 }; } let tabs = document.querySelectorAll('.tab'), i; for (i = 0; i < tabs.length; i += 1) { tabs[i].onclick = tabsHandler(i); }
While function expressions and function declarations are usually used interchangeably, there are some key differences to note. Function declarations are promoted, meaning they can be called before the declaration. On the other hand, function expressions are not promoted and therefore cannot be called before definition. Additionally, function expressions can be anonymous or named, while function declarations must always be named.
Function expressions provide some advantages. They can be anonymous, can be set to self-executable (call function expressions immediately), and can be assigned to variables and passed around. This makes function expressions very suitable for use as closures and callback functions.
Generally, the performance differences between function expressions and function declarations are negligible and are unlikely to affect the performance of JavaScript code. The choice of function expressions and function declarations should be based on your specific use case and coding style preferences.
Yes, function expressions are often used to create closures in JavaScript. A closure is a function that can access its own scope, the scope of external functions, and the global scope. Here is an example closure created using function expressions:
function funcDeclaration() { return '函数声明'; } let funcExpression = function () { return '函数表达式'; }
The above is the detailed content of When to Use a Function Expression vs. Function Declaration. For more information, please follow other related articles on the PHP Chinese website!