Arrow Functions
A shorter syntax for writing functions.
Syntax
const add = (a, b) => a + b;Arrow functions are a compact way to write functions, introduced in ES6.
Short forms
- One expression? The value is returned automatically (no braces, no
return). - One parameter? The parentheses are optional.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Pass a concise arrow function as a callback to Array.map to transform a list of prices.
- Write an event listener as an arrow function inside a class method so this refers to the class instance.
- Define a one-liner utility function that converts Celsius to Fahrenheit without a return keyword.
More examples
Arrow function basics
Shows single-parameter and two-parameter arrow functions with implicit returns.
const double = n => n * 2;
const add = (a, b) => a + b;
console.log(double(5)); // 10
console.log(add(3, 4)); // 7Arrow in Array.map
Uses an arrow function as the map callback to apply an 8% tax to each price.
const prices = [10, 25, 50];
const withTax = prices.map(p => p * 1.08);
console.log(withTax); // [10.8, 27, 54]Arrow preserves this in class
The arrow function inside setInterval captures the enclosing this from start(), so this.seconds refers to the Timer instance.
class Timer {
constructor() { this.seconds = 0; }
start() {
setInterval(() => { this.seconds++; }, 1000);
}
}
const t = new Timer();
t.start();
Discussion