Arrow Functions
In this page:
Basic Arrow Functions
An arrow function stores a function expression using the concise => syntax, for example const add = (a: number, b: number): number => a + b. It behaves like a regular function for typing purposes but with notably shorter syntax.
Example: Basic Arrow Functions
const add = (a: number, b: number): number => a + b;
console.log(add(3, 4));
Implicit Returns
When an arrow function's body is a single expression, that expression's result can be returned automatically without braces or an explicit return keyword. This implicit-return form is one of the biggest ergonomic wins arrow functions offer over regular function syntax.
Example: Implicit Returns
const square = (n: number) => n * n; // no braces, no explicit return
console.log(square(5));
Arrow Functions with Arrays
Arrow functions are extremely common as inline callbacks passed to array methods like map, filter, and reduce, precisely because their compact syntax keeps a short transformation readable in place. TypeScript infers the parameter types from the array's element type in these cases.
Example: Arrow Functions with Arrays
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);
console.log(doubled);
Arrow Functions with Multiple Parameters
Arrow functions can accept multiple typed parameters exactly like a regular function declaration, for example (a: number, b: number) => a * b. Type annotations on each parameter work identically whether the function uses arrow or traditional syntax.
Example: Arrow Functions with Multiple Parameters
const multiply = (a: number, b: number) => a * b;
console.log(multiply(6, 7));
When to Use Arrow Functions
Arrow functions are a good default choice for short, concise operations and callbacks, and they also don't rebind this the way regular functions do, which matters heavily inside classes and event handlers. Regular function declarations remain preferable when you need that dynamic this binding or hoisting.
Example: When to Use Arrow Functions
class Counter {
count = 0;
increment = () => {
this.count++; // arrow function keeps "this" bound to Counter
};
}
const c = new Counter();
c.increment();
console.log(c.count);
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: