JavaScript Arrow Functions Cheat Sheet

Basic Syntax

  • Arrow functions are concise alternatives to function.
  • No function keyword, and this is inherited (lexical).
  • Great for short, inline callbacks.
Pattern Syntax Example
Single param x => x * 2 Multiply by 2
Multiple params (a, b) => a + b Add two values
No params () => 'Hello' Return a string
Multi-line x => { const y = x * 2; return y; } Full block body

Array Methods

  • Arrow functions are perfect for functional array operations.
const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);
numbers.forEach(n => console.log(n));
const firstEven = numbers.find(n => n % 2 === 0);
const hasEven = numbers.some(n => n % 2 === 0);
const allPositive = numbers.every(n => n > 0);

Event Handlers

  • Use arrow functions to keep this lexical in callbacks.
// React/JSX
<button onClick={() => handleClick()}>Click me</button>;

// DOM
document.getElementById('btn').addEventListener('click', () => {
    console.log('Button clicked');
});

// With parameters
const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Form submitted');
};

Promise Chains

  • Use arrow functions for clean, chained .then() callbacks.
fetch('/api/data')
    .then(response => response.json())
    .then(data => data.items.map(item => item.name))
    .catch(error => console.error('Error:', error));

Rest Parameters

  • Use ...args to collect multiple inputs into one array.
const sum = (...numbers) => numbers.reduce((acc, n) => acc + n, 0);
const logArgs = (...args) => console.log(args);

Destructuring

  • Destructure objects and arrays right in the parameter list.
const getName = ({ name }) => name;
const getDetails = ({ name, age }) => `${name} is ${age} years old`;

const getFirst = ([first]) => first;
const swap = ([a, b]) => [b, a];

IIFE

  • Wrap in () to run immediately.
const result = (() => {
    const secret = 'hidden';
    return secret.toUpperCase();
})();

const config = ((apiKey, baseUrl) => ({
    apiKey,
    baseUrl,
    endpoint: `${baseUrl}/api`
}))('abc123', 'https://api.example.com');

Lexical `this` Binding

  • Arrow functions inherit this from the surrounding scope.
class Timer {
    constructor() {
        this.seconds = 0;
    }

    start() {
        setInterval(() => {
            this.seconds++;
            console.log(this.seconds);
        }, 1000);
    }
}

Regular vs Arrow Function (Context Differences)

  • Regular functions get dynamic this.
  • Arrow functions lock in this at definition time.
const obj = {
    name: 'Object',

    regularMethod: function () {
        setTimeout(function () {
            console.log(this.name); // undefined
        }, 100);
    },

    arrowMethod: function () {
        setTimeout(() => {
            console.log(this.name); // "Object"
        }, 100);
    }
};

When Not to Use Arrow Functions

  • Don't use them as object methods, constructors, or when this is required dynamically.

Object Methods

const calculator = {
    add: (a, b) => a + b, // 'this' won't refer to object
    multiply(a, b) { return a * b; } // Use regular function
};

Constructors

// ❌ Invalid constructor
const Person = (name) => { this.name = name; };

// ✅ Correct
function Person(name) {
    this.name = name;
}

DOM Event Handlers

// ❌ Arrow loses correct 'this'
element.addEventListener('click', () => {
    console.log(this); // Unexpected value
});

// ✅ Regular function preserves element context
element.addEventListener('click', function () {
    console.log(this); // Correct element
});

Memory Usage

  • Each arrow function creates a new instance.
const handlers = [];
for (let i = 0; i < 1000; i++) {
    handlers.push(() => console.log(i));
}

// Better: reuse a named function
const logIndex = (i) => console.log(i);
for (let i = 0; i < 1000; i++) {
    handlers.push(() => logIndex(i));
}

Hoisting

  • Arrow functions are not hoisted.
// ❌ ReferenceError
console.log(greet('John'));
const greet = (name) => `Hello, ${name}`;

// ✅ Works
console.log(greet('John'));
function greet(name) {
    return `Hello, ${name}`;
}