The arrow function is a shorthand function syntax, written as: (parameters) => expression. Its features include conciseness, the use of lexical scope binding, and no own this binding. Compared with traditional functions, arrow functions are more concise, lexically scoped, and have no this binding. Arrow functions are commonly used for callback functions, compact functions, and lexically scoped functions.
How to write arrow functions in JavaScript
The arrow function is a shorthand function syntax introduced in JavaScript. It can Make the code more concise and easier to read.
Writing
The arrow function is written as follows:
<code>(parameters) => expression</code>
Among them:
parameters
: The parameter list of the function (can be omitted). expression
: Function body, usually an expression (braces and return
statements can be omitted). Example
The following is an example of an arrow function:
<code>const sum = (a, b) => a + b;</code>
This function accepts two parameters a
and b
, and return their sum.
Features
Arrow functions have some characteristics:
return
statement. this
Binding: The arrow function does not have its own this
binding, but instead inherits the this of its outer function
Binding. Comparison with traditional functions
The following table compares arrow functions with traditional functions:
Features | Arrow function | Traditional function |
---|---|---|
(parameters) => expression | function (parameters) { ... } | |
More concise | More verbose | |
Lexical | Dynamic | |
Binding Inherit the outer function |
own | this Binding
|
Arrow functions are usually used in the following situations:
Callback functions (such as
Concise functionsThe above is the detailed content of How to write arrow function in js. For more information, please follow other related articles on the PHP Chinese website!