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.
const add = (a, b) => a + b; console.log(add(5, 3)); // Output: 8
const getObject = () => ({ key: 'value' }); console.log(getObject()); // Output: { key: 'value' }
const getArray = () => [1, 2, 3]; console.log(getArray()); // Output: [1, 2, 3]
const greet = (name) => `Hello, ${name}!`; console.log(greet('John')); // Output: Hello, John!
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.
// 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;