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
(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 withoutreturn.{ … }: the long form, for more than one line. Here you must writereturnto give a value back.
See Arrow function expressions (opens in a new tab) on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
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
const double = (n) => n * 2;
console.log(double(21));
const half = (n) => {
return n / 2;
};
console.log(half(42));
Step 2: Run It
node arrow.js
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
| Mistake | What happens | Do this instead |
|---|---|---|
Braces with no return: (n) => { n * 2; } | The function gives back undefined. Running it printed undefined | Leave 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
- Arrow function expressions (opens in a new tab) (MDN)
- Functions (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments