My Cheatsheets

TypeScript Lambdas and Closures for Dummies

1. What is a Lambda (Arrow Function)?

Example: Basic Lambda

const add = (x: number, y: number): number => x + y;
console.log(add(3, 5)); // Output: 8

Example: Lambda with Block Body

const sayHello = (name: string): void => {
    console.log(`Hello, ${name}!`);
};

sayHello("Alice"); // Output: Hello, Alice!

2. What is a Closure?

Example: Basic Closure

function makeCounter(): () => number {
    let count = 0;  // Remembered by the inner function
    return () => ++count;  // Closure function
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

3. Closures with Parameters

Example: Flexible Counter with Parameter

function makeCounter(start: number): (step: number) => number {
    let count = start;
    return (step: number) => count += step;
}

const counter = makeCounter(10);  // Starts at 10
console.log(counter(2)); // 12
console.log(counter(5)); // 17

4. Closures with Objects

Example: Counter with Reset Function

function makeCounter(start: number): { next: () => number, reset: () => void } {
    let count = start;
    return {
        next: () => ++count,
        reset: () => { count = start; }
    };
}

const counter = makeCounter(10);
console.log(counter.next()); // 11
console.log(counter.next()); // 12
counter.reset();
console.log(counter.next()); // 11

5. When to Use Lambdas vs. Closures?

Feature Use Lambda Use Closure
Short function (one-liner) ✅ Yes ❌ No
Needs to remember state ❌ No ✅ Yes
Works inside map(), filter(), etc. ✅ Yes ❌ No
Used for event handlers ✅ Yes ✅ Yes
Creates independent instances ❌ No ✅ Yes

🚀 Takeaway