Sunday, 19 January 2025

Understanding Arrow Functions in JavaScript: Implicit vs Explicit Return

In JavaScript, the way you define the body of an arrow function can change its behaviour.

 

1. Implicit Return (using parentheses ()):

If you use parentheses () for the body of an arrow function, it implies an implicit return. This means the expression inside the parentheses will be automatically returned without needing an explicit return keyword.

const userDetails = () => ({
  name: "Krishna",
  age: 36,
});

 

This is useful when the function body consists of a single expression, and you want to return the result of that expression directly.

 

Note

If the arrow function has single line body, you can directly return without wrapping it in ().

const add = (a, b) => a + b;

 

But if you want to return an object from an arrow function using implicit return, you must wrap the object in parentheses. This is because JavaScript interprets curly braces {} as the beginning of a function body, not an object, unless it's inside parentheses.

 

2. Explicit Return (using curly braces {}):

When you use curly braces {}, you need to explicitly specify the return statement if you want to return something from the function.

 

const personDetails = () => {
  return {
    name: "Ram",
    age: 66,
  };
};

implicit-vs-explicit-return.js

const userDetails = () => ({
  name: "Krishna",
  age: 36,
});

const personDetails = () => {
  return {
    name: "Ram",
    age: 66,
  };
};

console.log(`userDetails : ${JSON.stringify(userDetails())}`);
console.log(`personDetails : ${JSON.stringify(personDetails())}`);

const add = (a, b) => a + b;
console.log(`Sum of 10 and 20 is ${add(10, 20)}`);

Output

userDetails : {"name":"Krishna","age":36}
personDetails : {"name":"Ram","age":66}
Sum of 10 and 20 is 30


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment