Home > Web Front-end > JS Tutorial > Why Do Arrow Functions Need Explicit Returns When Using Block Declarations?

Why Do Arrow Functions Need Explicit Returns When Using Block Declarations?

Linda Hamilton
Release: 2024-12-18 09:54:18
Original
317 people have browsed it

Why Do Arrow Functions Need Explicit Returns When Using Block Declarations?

Why Arrow Functions Without Block Declarations Must Return Values Explicitly

Arrow functions, introduced in ES6, simplify the syntax of JavaScript functions. However, they can behave differently from regular functions when it comes to returning values.

Consider the following arrow function with a block declaration (enclosed in curly braces):

const f = arg => { arg.toUpperCase(); };
Copy after login

Invoking this function does not return a value, resulting in undefined being printed to the console:

console.log(f("testing")); // undefined
Copy after login

Unlike regular functions, arrow functions with block declarations do not return the result of the block expression implicitly. Instead, an explicit return statement is necessary to specify the return value. Thus, the arrow function should be written as:

const f = arg => { return arg.toUpperCase(); }; // Explicit 'return' statement
Copy after login

Alternatively, the arrow function can be declared concisely (without block braces). In this case, the result of the expression following the arrow is implicitly returned:

const f = arg => arg.toUpperCase();
Copy after login

Examples:

const f1 = arg => { return arg.toUpperCase(); }; // With explicit 'return'
console.log(f1("testing"));

const f2 = arg => arg.toUpperCase(); // Concise arrow function
console.log(f2("testing"));
Copy after login

Both f1 and f2 return the upper-case string "TESTING". By understanding the difference between arrow functions with and without block declarations, you can ensure that your arrow functions return the expected values.

The above is the detailed content of Why Do Arrow Functions Need Explicit Returns When Using Block Declarations?. For more information, please follow other related articles on the PHP Chinese website!

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