Skip to content

JavaScript cheat sheet

Modern JavaScript (ES2023) on one page. Snippets that log output open in the JavaScript playground with one click.

31 entries

Variables & types

const pi = 3.14
let count = 0
count += 1

const cannot be reassigned; let is block-scoped. Avoid var.

typeof 42        // "number"
typeof "hi"      // "string"
typeof null      // "object" (historic quirk)

typeof operator.

const name = "Ada"
console.log(`Hello, ${name}!`)

Template literals interpolate with ${}.

const port = config.port ?? 3000
const city = user?.address?.city

Nullish coalescing and optional chaining.

0 == "0"   // true  (coerces)
0 === "0"  // false (strict)

Prefer === and !==.

Functions

function add(a, b = 0) { return a + b }

Function declaration with default parameter.

const add = (a, b) => a + b
const toObj = (x) => ({ x })

Arrow functions; wrap an object literal in parentheses.

const sum = (...nums) => nums.reduce((a, n) => a + n, 0)
console.log(sum(1, 2, 3))

Rest parameters collect arguments into an array.

function counter() {
  let n = 0
  return () => ++n
}
const next = counter()
console.log(next(), next())

Closures remember the scope they were created in.

Arrays

const nums = [1, 2, 3, 4]
console.log(nums.map((n) => n * 2))

map transforms every item into a new array.

const nums = [1, 2, 3, 4]
console.log(nums.filter((n) => n % 2 === 0))

filter keeps items that pass the test.

const nums = [1, 2, 3, 4]
console.log(nums.reduce((sum, n) => sum + n, 0))

reduce folds an array into one value.

const users = [{ id: 1 }, { id: 2 }]
console.log(users.find((u) => u.id === 2))

find returns the first match or undefined.

const a = [3, 1, 2]
console.log(a.toSorted(), a)

toSorted / toReversed (ES2023) return copies; sort mutates.

const merged = [...[1, 2], ...[3]]
console.log(merged, merged.at(-1))

Spread to copy/merge; at(-1) reads the last item.

Objects & destructuring

const user = { name: "Ada", age: 36 }
const { name, age: years } = user
console.log(name, years)

Object destructuring with renaming.

const [first, , third = 0] = [10, 20]
console.log(first, third)

Array destructuring with skip and default.

const base = { a: 1 }
const copy = { ...base, b: 2 }
console.log(copy)

Spread copies (shallow) and extends objects.

const user = { name: "Ada", age: 36 }
for (const [k, v] of Object.entries(user)) console.log(k, v)

Object.keys / values / entries.

const deep = structuredClone({ a: { b: 1 } })

structuredClone makes a deep copy.

Classes

class Animal {
  #sound = "..."
  constructor(name) { this.name = name }
  speak() { return `${this.name}: ${this.#sound}` }
  static create(n) { return new Animal(n) }
}
console.log(Animal.create("Rex").speak())

Class fields, #private fields, static methods.

class Dog extends Animal {
  speak() { return super.speak() + " woof" }
}

Inheritance with extends / super.

Async

const wait = (ms) => new Promise((r) => setTimeout(r, ms))
await wait(100)
console.log("100 ms later")

Wrap callbacks in a Promise; await pauses the async function.

async function getJson(url) {
  const res = await fetch(url)
  if (!res.ok) throw new Error(res.status)
  return res.json()
}

fetch + async/await with error check.

const [a, b] = await Promise.all([Promise.resolve(1), Promise.resolve(2)])
console.log(a, b)

Run promises in parallel; rejects if any rejects.

const results = await Promise.allSettled([Promise.reject(new Error("x")), 1])
console.log(results.map((r) => r.status))

allSettled never rejects.

try {
  await Promise.reject(new Error("boom"))
} catch (e) {
  console.log("caught", e.message)
}

try/catch works with await.

Modules & misc

export const pi = 3.14
export default function main() {}

Named and default exports.

import main, { pi } from "./math.js"
const mod = await import("./big.js")

Static and dynamic import.

JSON.stringify({ a: 1 }, null, 2)
JSON.parse('{"a":1}')

Serialize and parse JSON.

const m = new Map([["a", 1]])
const s = new Set([1, 1, 2])
console.log(m.get("a"), s.size)

Map (any key type) and Set (unique values).

Frequently asked questions

What is the difference between let, const and var?

const and let are block-scoped; const cannot be reassigned (though objects it points to can still change). var is function-scoped and hoisted, which causes subtle bugs, so modern code avoids it.

When should I use map vs forEach?

Use map when you want a new array of transformed values. Use forEach (or a for…of loop) when you only need side effects and no return value.

Can I run these snippets here?

Yes. Snippets that print with console.log have a Run button that opens them in the JavaScript playground, which executes them in a sandboxed Web Worker in your browser.

Related cheat sheets