Home > Web Front-end > JS Tutorial > How to write arrow function in js

How to write arrow function in js

下次还敢
Release: 2024-05-01 07:33:16
Original
828 people have browsed it

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 function in js

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>
Copy after login

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>
Copy after login

This function accepts two parameters a and b, and return their sum.

Features

Arrow functions have some characteristics:

  • Conciseness:Arrow functions are more concise than traditional functions, Because it omits the curly braces and return statement.
  • Binding: The arrow function uses lexical scope, not dynamic scope, so it is always bound to the context in which it is defined.
  • Nonethis 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:

##Syntax(parameters) => expression function (parameters) { ... }SuccinctnessMore conciseMore verboseScope LexicalDynamic##thisthis
Features Arrow function Traditional function
Binding Inherit the outer function own Binding
When to use arrow functions

Arrow functions are usually used in the following situations:

Callback functions (such as
    Array.map
  • )Concise functions
  • Required Lexically scoped functions

The 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template