DEV Community

Bunlong
Bunlong

Posted on

1 1

Arrow Functions Return Rules in JavaScript

Arrow Functions Return Rules in JavaScript

There are 2 ways for returning values in arrow functions:

  1. Explicit Return
  2. Implicit Return

1. Explicit Return

What is Explicit Return?

A function is returned values using the return keyword, it’s called an explicit return.

The Rules of Explicit Return

You must use an explicit return statement in a block body.

Example

// Single-line
const explicit = (value) => { return value; }

// Multi-line
const explicit = (value) => {
  return value;
}

2. Implicit Return

What is Implicit Return?

A function is returned values without using the return keyword, it’s called an implicit return.

The Rules of Implicit Return

You must use an implicit return in a concise body.

Example

// Single-line
const implicit = (value) => value;

// Multi-line
const implicit = (value) => (
  value
);

Issue Returning Objects

When using implicit returns, object literals must be wrapped in parenthesis so that the curly braces are not mistaken for the opening of the function’s body.

const implicit = () => { value: 1 };
implicit(); // undefined

const implicit = () => ({ value: 1 });
implicit(); // { value: 1 }

Parens Rules

Arrow functions can omit parentheses when they have exactly one parameter.

// Arrow Functions, with parentheses
const myFunction = (p) => {}

// Arrow Functions, without parentheses
const myFunction = p => {}

In all other cases (multiple parameters), the parameter(s) must be wrapped in parentheses.

// Arrow Function, with parentheses
const myFunction = (p1, p2) => {}

References

Thanks for reading ❤ Say Hello! Github | LinkedIn | Twitter

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay