JavaScript Arrow Functions Cheat Sheet

⚑ Basic Syntax

  • Arrow functions are shorter than function
  • They inherit this from their scope (lexical)
  • Great for one-liners and callbacks
Pattern Syntax Description
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 with return

πŸ”„ Array Methods

  • Ideal for short, expressive callbacks
  • Common with .map(), .filter(), .reduce()
  • Keeps your code concise
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

  • Lexical this is perfect for React and DOM
  • No need to bind methods manually
  • Use for inline behavior
// React
<button onClick={() => doThing()}>Click</button>;

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

// With arguments
const handleSubmit = (e) => {
  e.preventDefault();
  console.log('Submitted');
};

πŸ”— Promise Chains

  • Keeps .then() chains readable
  • Shortens boilerplate
fetch('/api/data')
  .then(res => res.json())
  .then(data => data.items.map(i => i.name))
  .catch(err => console.error('Error:', err));

πŸ“¦ Rest Parameters

  • Use ...args to collect inputs
  • Works well with reduce()
const sum = (...nums) => nums.reduce((a, n) => a + n, 0);
const log = (...args) => console.log(args);

🧩 Destructuring

  • Pull values right in the param list
  • Works with objects and arrays
const getName = ({ name }) => name;
const getAgeText = ({ name, age }) => `${name} is ${age}`;

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

πŸš€ IIFE (Immediately Invoked)

  • Arrow functions can run instantly
  • Use for config or temporary logic
const result = (() => {
  const secret = 'hidden';
  return secret.toUpperCase();
})();

const config = ((key, base) => ({
  key,
  base,
  url: `${base}/api`
}))('abc123', 'https://api.com');

πŸ”’ Lexical `this` Binding

  • Arrow functions don't rebind this
  • Use them to retain object context
class Timer {
  constructor() {
    this.seconds = 0;
  }

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

πŸ”„ Arrow vs Regular Function

  • Regular functions have dynamic this
  • Arrow functions keep the outer this
const obj = {
  name: 'Object',

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

  arrowMethod() {
    setTimeout(() => {
      console.log(this.name); // βœ… "Object"
    }, 100);
  }
};

🚫 When *Not* to Use Arrow Functions

❌ As Object Methods

const calculator = {
  add: (a, b) => a + b, // ❌ No `this`
  multiply(a, b) { return a * b; } // βœ… Regular function
};

❌ As Constructors

// ❌ Won’t work
const Person = (name) => { this.name = name; };

// βœ… Use function
function Person(name) {
  this.name = name;
}

❌ In DOM Event Handlers

// ❌ Arrow function β€” wrong `this`
element.addEventListener('click', () => {
  console.log(this); // ❌ not the element
});

// βœ… Regular function β€” correct `this`
element.addEventListener('click', function () {
  console.log(this); // βœ… the element
});

πŸ’Ύ Memory Usage

  • New function is created each time
  • Use named functions to reuse logic
const handlers = [];
for (let i = 0; i < 1000; i++) {
  handlers.push(() => console.log(i));
}

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

⏫ Hoisting

  • Arrow functions are not hoisted
  • Must define before using
// ❌ Error
console.log(greet('John'));
const greet = (name) => `Hi, ${name}`;

// βœ… Works
console.log(greet('John'));
function greet(name) {
  return `Hi, ${name}`;
}