java-script:arrow-function-implicit-return
Table of Contents
Java Script Arrow Functions Implicit Return
Arrow functions allow for a concise syntax that can include an implicit return.
Syntax:
const functionName = (parameters) => expression;
The expression right after the ⇒ will be implicitly returned. This is particularly useful for simple, one-liner functions.
Implicit return occurs only when curly braces {} are not used.
When you use curly braces {} in an arrow function, it indicates a block of code, and you will need to include an explicit return statement to return a value.
If you don't include a return statement, the function will return undefined.
If you don't include a return statement, the function will return undefined.
Implicitly Returning a Number
const add = (a, b) => a + b; console.log(add(5, 3)); // Output: 8
Implicitly Returning an Object
const getObject = () => ({ key: 'value' }); console.log(getObject()); // Output: { key: 'value' }
Implicitly Returning an Array
const getArray = () => [1, 2, 3]; console.log(getArray()); // Output: [1, 2, 3]
Implicitly Returning a String
const greet = (name) => `Hello, ${name}!`; console.log(greet('John')); // Output: Hello, John!
Other considerations
If the body of the arrow function requires more complex logic or multiple statements, you'll need to use braces {} and an explicit return statement:
const add = (a, b) => { //other code here... return a + b; // explicit return needed }; console.log(add(5, 3)); // Output: 8
Implicit return only works for a single expression.
We can't have an explicit return statement without using the curly braces {} in an arrow function. The explicit return requires a block of code, and curly braces are used to define that block.
Not working example:
Not working example:
// Syntax error, unexpected token 'return' const add = (a, b) => return a + b;
To fix the code, remove the return keyword or add curly braces:
// This works, added curly braces const add = (a, b) => { return a + b; }
// This works, return keyword removed. const add = (a, b) => a + b;
java-script/arrow-function-implicit-return.txt · Last modified: 2023/08/10 13:56 by odefta