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

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay