← Back to TypeScript Course | Chapter 3: Variables and Functions | Lesson 9 of 10

Arrow Functions

Arrow functions provide a concise syntax for writing functions in TypeScript. They are especially useful for short functions, callbacks, and array operations.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
class Counter {
  count = 0;
  increment = () => {
    this.count++; // arrow function keeps "this" bound to Counter
  };
}
const c = new Counter();
c.increment();
console.log(c.count);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.