Home  >  Article  >  Web Front-end  >  What is the return value of arrow function in js

What is the return value of arrow function in js

下次还敢
下次还敢Original
2024-05-06 13:51:141043browse

The return value rules of arrow functions: If the function body is an expression, the expression value is returned. If the function body is a block, the last expression value in the block is returned. If the function body is empty, undefined is returned.

What is the return value of arrow function in js

The return value of JavaScript arrow function

The arrow function is a kind of syntax sugar that simplifies function expressions. Introduced in ES6. Unlike traditional functions, arrow functions do not have their own this binding and can automatically return based on an expression.

Return value rules

The return value of an arrow function is determined by the following rules:

  • If the function body contains an expression, then the The expression is the return value.
  • If the function body contains a block, the value of the last expression in the block is the return value.
  • If the function body does not contain any expressions or blocks, it returns undefined by default.

Example

<code class="javascript">// 返回表达式
const add = (a, b) => a + b;

// 返回块中最后一个表达式的值
const subtract = (a, b) => {
  const diff = a - b;
  return diff;
};

// 返回 undefined
const noReturn = () => {};</code>

Application scenarios

Arrow functions are usually used in the following scenarios:

  • as callback functions since they are more concise and don't have this binding issues.
  • As constructors because they can easily attach new properties to instances.
  • As filters because they allow complex filtering conditions to be written more concisely.

Note:

Although arrow functions are convenient, they may not be suitable for use in the following situations:

  • Required arguments Object.
  • Needs to bind custom this value.
  • Need to access the new.target property of the constructor.

The above is the detailed content of What is the return value of arrow function in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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