ES6+ Cheatsheet

Modern JavaScript features — let/const, destructuring, modules & more

Language
Contents
📌

Variables

let x = 10;        // block-scoped, reassignable
const y = 20;      // block-scoped, constant ref
// var is function-scoped — avoid in modern code

// const doesn't mean immutable
const arr = [1,2];
arr.push(3);       // OK — mutating content
// arr = [4,5];    // Error — reassignment

Arrow Functions

// Concise syntax
const add = (a, b) => a + b;
const sq = x => x * x;          // single param
const greet = () => "hi";       // no params

// Multi-line body
const calc = (a, b) => {
    const sum = a + b;
    return sum * 2;
};

// Return object literal (wrap in parens)
const make = (name) => ({ name, active: true });

// No own `this` — inherits from enclosing scope
const obj = {
    items: [1,2,3],
    log() { this.items.forEach(i => console.log(i)); }
};
📦

Destructuring

// Array destructuring
const [a, b, ...rest] = [1, 2, 3, 4];
// a=1, b=2, rest=[3,4]

// Skip elements
const [, second] = [10, 20];

// Object destructuring
const { name, age } = user;
const { name: n, age: a } = user;  // rename
const { x = 10 } = {};             // default

// Nested
const { address: { city } } = user;

// Function params
function greet({ name, age = 0 }) {
    return `${name} is ${age}`;
}
💬

Template Literals

// Interpolation
const msg = `Hello, ${name}!`;
const math = `2+3 = ${2+3}`;

// Multi-line
const html = `
<div>
  <h1>${title}</h1>
  <p>${body}</p>
</div>`;

// Tagged templates
function highlight(strings, ...values) {
    return strings.reduce((r, s, i) =>
        `${r}${s}<b>${values[i]||''}</b>`, '');
}
const out = highlight`Hello ${name}, age ${age}`;
🔄

Spread & Rest

// Spread — expand iterable
const a = [1, 2, 3];
const b = [...a, 4, 5];    // [1,2,3,4,5]
const copy = [...a];        // shallow copy

// Object spread
const obj = { ...defaults, ...overrides };

// Rest — collect remaining
function sum(...nums) {
    return nums.reduce((t, n) => t + n, 0);
}

// Rest in destructuring
const { id, ...rest } = user;
📥

Modules

// Named exports
export const PI = 3.14;
export function add(a, b) { return a + b; }

// Default export
export default class User { }

// Import named
import { PI, add } from './math.js';

// Import default
import User from './User.js';

// Import all
import * as math from './math.js';

// Dynamic import
const mod = await import('./heavy.js');

// Re-export
export { add } from './math.js';
🔮

Promises & Async/Await

// Promise
const p = new Promise((resolve, reject) => {
    setTimeout(() => resolve('done'), 1000);
});
p.then(val => console.log(val))
 .catch(err => console.error(err))
 .finally(() => console.log('finished'));

// Promise combinators
Promise.all([p1, p2])         // all resolve
Promise.allSettled([p1, p2])  // all complete
Promise.race([p1, p2])        // first to settle
Promise.any([p1, p2])         // first to resolve

// Async / Await
async function fetchData() {
    try {
        const res = await fetch('/api/data');
        const data = await res.json();
        return data;
    } catch (err) {
        console.error(err);
    }
}
🏗️

Classes

class Animal {
    #name;  // private field
    constructor(name) { this.#name = name; }
    speak() { return `${this.#name} speaks`; }
    get info() { return this.#name; }
    static create(n) { return new Animal(n); }
}

class Dog extends Animal {
    constructor(name, breed) {
        super(name);
        this.breed = breed;
    }
    speak() { return `${super.speak()} — Woof!`; }
}

Misc Features

// Optional chaining
user?.address?.city          // undefined if null

// Nullish coalescing
const name = input ?? 'default';   // only null/undefined

// Logical assignment
x ??= 5;  x ||= 5;  x &&= 5;

// for..of  (iterables)
for (const item of arr) { }

// Map & Set
const m = new Map();  m.set('k', 'v');
const s = new Set([1,2,2,3]); // {1,2,3}

// Symbol
const id = Symbol('id');

// Array methods
arr.find(x => x > 3)    arr.findIndex(...)
arr.includes(5)        arr.flat(2)
arr.flatMap(fn)         Object.entries(obj)
Object.fromEntries(entries)