JavaScript Arrow Functions
An arrow function is a short way to write a function. It uses an arrow, =>, instead of the function keyword.
Both forms
An arrow function is a short way to write a function, as the second form shows. Both forms log the same result here.
function doubleA(n) {
return n * 2;
}
const doubleB = (n) => n * 2;
console.log(doubleA(6));
console.log(doubleB(6));One parameter
The single parameter n stands without parentheses here. The one-line body returns the tripled value.
const triple = n => n * 3;
console.log(triple(4));A body in braces
This body holds two lines inside braces. The second line returns the total with the return keyword.
const add = (a, b) => {
const total = a + b;
return total;
};
console.log(add(3, 5));Example
const square = n => n * n;
const greet = (name) => {
const message = "Hello, " + name;
return message;
};
console.log(square(5));
console.log(greet("Ana"));Key points
- One parameter needs no parentheses around its name.
- Zero parameters still need empty parentheses, such as () => 5.
- A one-line body returns its value without the return keyword.
- A body in braces needs the return keyword to send a value back.
- The arrow => sits between the parameters and the body.
In this example, square holds a one-line arrow function with one parameter. Its body returns 25 for the argument 5, and the caller logs it. The greet function holds a body in braces with two lines. That body builds a message and returns it, and the caller logs "Hello, Ana".
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does a one-line arrow function body do with its value?