Skip to main content
0 reactions

How to Write an Arrow Function in JavaScript

Card titled Arrow Functions in JavaScript, labelled JavaScript basics, with four ticked lines: (n) => n * 2, double(21) gives 42, a body in braces with return n / 2, and braces with no return give undefined.
How to Write an Arrow Function in JavaScript

An arrow function is a short way to write a function in JavaScript. You write its inputs in brackets, an arrow =>, and what it gives back.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
(input) => result

(input) => {
  return result;
}
  • (input): the values the function takes, called parameters, separated by commas. Write () when it takes none.
  • =>: the arrow that makes it an arrow function.
  • result: in the short form, the one expression after the arrow. The function gives back its value without return.
  • { … }: the long form, for more than one line. Here you must write return to give a value back.

See Arrow function expressions (opens in a new tab) on MDN.

Prerequisites

The Example

Two small functions in a file named arrow.js: double in the short form and half with braces. Each is stored in a constant, so you call it by that name.

Step 1: Write the Code

arrow.jsJavaScript
const double = (n) => n * 2;
console.log(double(21));

const half = (n) => {
  return n / 2;
};
console.log(half(42));

Step 2: Run It

TerminalBash
node arrow.js
OutputPlain text
42
21

double(21) gives 42 from the short form. half(42) gives 21 from the form with braces, because of its return.

Common Mistakes

MistakeWhat happensDo this instead
Braces with no return: (n) => { n * 2; }The function gives back undefined. Running it printed undefinedLeave out the braces, (n) => n * 2, or write return inside them

FAQ

Is an arrow function the same as a normal function?

For simple jobs like these, yes: both take inputs and give back a value. They differ in details, such as what this means inside them.

Why does the arrow sit inside other code so often?

Because it’s short, it’s the usual way to hand a small function to another one, such as prices.map((price) => price * 2).

Conclusion

Write (input) => result for a one-line function. When you use braces, add return, or the function gives back undefined.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments