Home >Web Front-end >JS Tutorial >Difference between ( )=>{ } and ( )=>( ) aero function in JavaScript (JS)
{ } and ( )=>( ) aero function in JavaScript (JS)" />
The difference between ()=>{} and ()=>() lies in how they handle function bodies and return statements in JavaScript. Both are arrow functions, but they behave slightly differently depending on the syntax used.
const add = (a, b) => { return a + b; // Explicit return }; console.log(add(2, 3)); // Output: 5
const add = (a, b) => a + b; // Implicit return console.log(add(2, 3)); // Output: 5
Example:
const processNumbers = (a, b) => { const sum = a + b; const product = a * b; return sum + product; // Explicitly return the result }; console.log(processNumbers(2, 3)); // Output: 11
Example:
const square = (x) => x * x; // Implicit return console.log(square(4)); // Output: 16
If you want to return an object literal using an implicit return, you need to wrap it in parentheses. Otherwise, JavaScript interprets the {} as a function body.
Example:
const add = (a, b) => { return a + b; // Explicit return }; console.log(add(2, 3)); // Output: 5
Syntax | Behavior | Example |
---|---|---|
()=>{} | Full function body, explicit return | const add = (a, b) => { return a b; }; |
()=>() | Single-line implicit return | const add = (a, b) => a b; |
Choose between the two based on your use case: clarity for complex functions (()=>{}) vs. concise syntax for simple functions (()=>()).
The above is the detailed content of Difference between ( )=>{ } and ( )=>( ) aero function in JavaScript (JS). For more information, please follow other related articles on the PHP Chinese website!