JavaScript ES6+ Cheatsheet
Every essential modern JavaScript pattern: variables, functions, arrays, objects, promises, async/await, and modules, with syntax and real use cases.88 commands · 8 sections
Modern JavaScript (ES6+) changed how the language is written. This cheatsheet covers the patterns you use daily: variables and scoping, arrow functions, destructuring, spread, template literals, array methods, promises and async/await, modules, and classes.
Every entry shows real syntax followed by the use case: when and why you reach for it.
Variables & Scoping8
const x = 42let x = 42var x = 1typeof xx ?? "default"x || "default"x?.proplet x = 1, y = 2; [x, y] = [y, x]Functions & Arrow Functions8
const add = (a, b) => a + bconst add = (a, b) => { return a + b }function greet(name) { ... }(arg) => argfunction f(...args) { }function f(a = 10) { }f.bind(this)fn.call(thisArg, a, b) / fn.apply(thisArg, [a, b])Objects & Arrays25
const o = { name: "x" }; o.age = 30const { name, age } = oconst { a = 1 } = oconst { a: alias } = oconst { ...rest } = oconst merged = { ...a, ...b }Object.keys(o) / Object.values(o) / Object.entries(o)Object.fromEntries(arr)Object.assign({}, a, b)arr.map(x => x * 2)arr.filter(x => x > 0)arr.reduce((acc, x) => acc + x, 0)arr.find(x => x.id === 42)arr.findIndex(x => x.id === 42)arr.some(x => x > 10) / arr.every(x => x > 10)arr.includes(x)arr.sort((a, b) => a - b)arr.slice(1, 3)arr.splice(1, 1, "new")arr.flat(2)arr.flatMap(x => [x, x * 2])[...new Set(arr)]Array.from({ length: 5 }, (_, i) => i)arr.forEach(x => ...)arr.at(-1)Destructuring & Spread9
const [first, second] = arrconst [, second] = arrconst [a = 0] = arrconst [...rest] = arrconst { length } = "hello"function f({ name, age }) { }function f({ a = 1 } = {}) { }const copy = [...arr][...a, ...b]Strings & Template Literals10
`Hello ${name}``multi
line
string`str.trim()str.split(",")arr.join(", ")str.includes("x") / str.startsWith("a") / str.endsWith("b")str.replaceAll("a", "b")str.padStart(5, "0")str.slice(0, 10)str.repeat(3)Promises & Async11
new Promise((resolve, reject) => { ... })fetch(url).then(r => r.json()).then(...).catch(e => ...)Promise.all([p1, p2])Promise.allSettled([p1, p2])Promise.race([p1, p2])Promise.any([p1, p2])async function f() { await x }try { await x } catch (e) { }async () => { }const timeout = ms => new Promise(res => setTimeout(res, ms))Modules & Imports8
import { x } from "./mod.js"import x from "./mod.js"import * as utils from "./mod.js"import { x as y } from "./mod.js"export const x = 42export default function f() { }export { a, b }const m = await import("./mod.js")Classes & Modern Syntax9
class User {
constructor(name) { this.name = name }
}class Admin extends User { }class X { #private = 1 }class X { static create() { } }class X { get value() { } }Symbol("id")for (const x of arr)for (const k in obj)label:
for (...) { break label }JavaScript ES6+ Cheatsheet
Every essential modern JavaScript pattern: variables, functions, arrays, objects, promises, async/await, and modules, with syntax and real use cases.
Modern JavaScript (ES6+) changed how the language is written. This cheatsheet covers the patterns you use daily: variables and scoping, arrow functions, destructuring, spread, template literals, array methods, promises and async/await, modules, and classes.
Every entry shows real syntax followed by the use case: when and why you reach for it.
Variables & Scoping
const x = 42: Constant binding: use by default; reassignment throws.let x = 42: Reassignable block-scoped variable: for counters and mutable state.var x = 1: Function-scoped legacy declaration: avoid in modern code.typeof x: Check a value's type at runtime.x ?? "default": Nullish coalescing: fallback only for null/undefined, not 0 or "".x || "default": Logical OR fallback: falls back for ALL falsy values.x?.prop: Optional chaining: safe access without TypeError.let x = 1, y = 2; [x, y] = [y, x]: Swap variables without a temp.Functions & Arrow Functions
const add = (a, b) => a + b: Arrow function with implicit return: short callbacks.const add = (a, b) => { return a + b }: Arrow function with explicit body: multiple statements.function greet(name) { ... }: Function declaration: hoisted, has its own this.(arg) => arg: Implicit-return arrow: the standard map/filter callback.function f(...args) { }: Rest parameters: collect remaining arguments.function f(a = 10) { }: Default parameter values.f.bind(this): Bind this explicitly: legacy; prefer arrows.fn.call(thisArg, a, b) / fn.apply(thisArg, [a, b]): Invoke with a custom this: call vs apply differ in args style.Objects & Arrays
const o = { name: "x" }; o.age = 30: Create and mutate an object: even const objects are mutable.const { name, age } = o: Object destructuring: pull properties into variables.const { a = 1 } = o: Destructure with a default: missing keys get fallback.const { a: alias } = o: Destructure with renaming.const { ...rest } = o: Object rest: everything except the named keys.const merged = { ...a, ...b }: Spread merge: b overrides a. Shallow only.Object.keys(o) / Object.values(o) / Object.entries(o): Iterate over an object.Object.fromEntries(arr): Build an object from [key, value] pairs.Object.assign({}, a, b): Shallow merge into a new object: legacy spread alternative.arr.map(x => x * 2): Transform every element into a new array.arr.filter(x => x > 0): Keep only matching elements.arr.reduce((acc, x) => acc + x, 0): Fold an array into a single value.arr.find(x => x.id === 42): First matching element (the element itself).arr.findIndex(x => x.id === 42): Index of the first match: -1 if absent.arr.some(x => x > 10) / arr.every(x => x > 10): Any / all elements match a condition.arr.includes(x): Primitive membership check.arr.sort((a, b) => a - b): Numeric sort: always pass a comparator.arr.slice(1, 3): Copy a subarray: slice is non-destructive.arr.splice(1, 1, "new"): Remove/replace items IN PLACE: mutates the array.arr.flat(2): Flatten nested arrays.arr.flatMap(x => [x, x * 2]): Map then flatten one level: one-to-many transforms.[...new Set(arr)]: Deduplicate an array.Array.from({ length: 5 }, (_, i) => i): Generate arrays: ranges and fills.arr.forEach(x => ...): Side-effect iteration: logging, DOM updates.arr.at(-1): Last element without arr[arr.length - 1].Destructuring & Spread
const [first, second] = arr: Array destructuring: pull by position.const [, second] = arr: Skip elements with empty slots.const [a = 0] = arr: Array destructure with default: empty slots get fallback.const [...rest] = arr: Rest element: everything after the named ones.const { length } = "hello": Destructure from any object: even strings.function f({ name, age }) { }: Destructure parameters: named options objects.function f({ a = 1 } = {}) { }: Fully defaulted options parameter: no undefined destructure crash.const copy = [...arr]: Shallow-copy an array: safe to sort/mutate the copy.[...a, ...b]: Concatenate arrays.Strings & Template Literals
`Hello ${name}`: Template literal: interpolation.`multi
line
string`: Multi-line strings without \n escaping.str.trim(): Strip surrounding whitespace.str.split(","): Split into an array.arr.join(", "): Join an array into a string.str.includes("x") / str.startsWith("a") / str.endsWith("b"): Substring checks: the modern indexOf replacements.str.replaceAll("a", "b"): Replace EVERY occurrence (ES2021).str.padStart(5, "0"): Left-pad: zero-padded ids and numbers.str.slice(0, 10): Substring by indices.str.repeat(3): Repeat a string.Promises & Async
new Promise((resolve, reject) => { ... }): Create a promise: wrap async work.fetch(url).then(r => r.json()): Chain promises: fetch + parse..then(...).catch(e => ...): Handle rejection: attach catch at the end.Promise.all([p1, p2]): Wait for ALL promises: parallel requests; rejects fast on any failure.Promise.allSettled([p1, p2]): Wait for all, keeping successes AND failures: partial results.Promise.race([p1, p2]): First to settle wins: timeouts.Promise.any([p1, p2]): First to FULFILL wins: ignore early rejections.async function f() { await x }: Async function: await inside without callback soup.try { await x } catch (e) { }: Handle async errors: try/catch works with await.async () => { }: Async arrow function: IIFE pattern for top-level await.const timeout = ms => new Promise(res => setTimeout(res, ms)): Sleep helper: await timeout(1000).Modules & Imports
import { x } from "./mod.js": Named import.import x from "./mod.js": Default import: the module's main export.import * as utils from "./mod.js": Namespace import: everything under one object.import { x as y } from "./mod.js": Rename imports.export const x = 42: Export a declaration inline.export default function f() { }: Default export: main API of a module.export { a, b }: Export selected names from a module.const m = await import("./mod.js"): Dynamic import: lazy-load heavy modules on demand.Classes & Modern Syntax
class User {
constructor(name) { this.name = name }
}: ES6 class: constructor and methods.class Admin extends User { }: Inheritance: subclass a class.class X { #private = 1 }: Private fields: # prefix, truly private (ES2022).class X { static create() { } }: Static method: call without an instance.class X { get value() { } }: Getter: computed properties.Symbol("id"): Unique symbol: private-ish keys and well-known protocol markers.for (const x of arr): Iterate values: the modern loop.for (const k in obj): Iterate object keys: with own/proto caveats; prefer Object.keys.label:
for (...) { break label }: Labeled loops: break/continue an outer loop.Frequently asked questions
What is the difference between var, let and const?
var is function-scoped and hoisted with undefined initialization. let and const are block-scoped with temporal dead zones. Use const by default, let when rebinding, and avoid var entirely.
How do Promises and async/await work together?
A Promise represents an eventual value. await suspends an async function until a Promise settles, making async code read like sync code. Always wrap await in try/catch or attach .catch() to handle rejections.
What does destructuring do?
Destructuring unpacks values from arrays or properties from objects into variables: const { name, age } = user and const [first, second] = arr. It also works in function parameters and for swapping values.
What is the difference between == and ===?
=== compares both value and type without coercion, so 0 === false is false. == performs type coercion first, making 0 == false true. Always use === (and Object.is for special cases).