JavaScript cheat sheet

A scannable JavaScript reference: 23 short snippets across 9 topics, each linking back to the lesson it came from.

At a glance

TopicWhat it covers
JavaScript basicsEverything else — arrays, functions, dates, regular expressions — is an object. This is why typeof null returninglesson
Functions and scopelet and const are block-scoped; var is function-scoped. A closure is simply a function that keeps access to variableslesson
Arrays and iterationThe methods that replace most for-loops — map, filter, reduce, find — and when mutation versus copying matterslesson
Objects and destructuringObjects are copied by reference: assigning one does not clone it, so both variables point at the same datalesson
Working with the DOMquerySelectorAll returns a static NodeList; getElementsByClassName returns a live HTMLCollection that updates as thelesson
EventsAn event travels three phases: capture down from the root, the target, then bubble back up. Listeners default to thelesson
Async JavaScript and fetchA promise is a placeholder for a value that is not ready yet. It settles once — either fulfilled with a value, orlesson
Modules and project structureAn ES module has its own scope, is always strict, and runs once no matter how many times it is imported. Imports arelesson
Tooling: linting, formatting, bundling and testingPrettier decides layout — indentation, quotes, line breaks — and never argues about meaning. ESLint finds likely bugslesson

Quick snippets

JavaScript basics

Declaring variables

const rate = 0.2;   // cannot be reassigned
let count = 0;      // can be reassigned
count += 1;

// var is function-scoped and hoisted - avoid it in new code
var legacy = true;

Coercion and equality

'5' == 5     // true  - coerces types first
'5' === 5    // false - different types
null == undefined   // true
null === undefined  // false

0 == false    // true
'' == false   // true
'0' == false  // true   <- the famous trap

Running your code

console.log('value:', 42);
console.table([{ id: 1, ok: true }]);

// in the browser
<script type='module' src='/app.js'></script>

Full lesson: JavaScript basics →

Functions and scope

Scope and closures

function makeCounter() {
  let n = 0;                 // private to each counter
  return () => ++n;
}
const next = makeCounter();
next(); // 1
next(); // 2

Understanding this

const obj = {
  n: 1,
  inc() { this.n += 1; }        // method shorthand: this === obj
};

const inc = obj.inc;
inc();  // TypeError - lost its receiver

const safe = obj.inc.bind(obj); // permanently attached
safe();

Full lesson: Functions and scope →

Arrays and iteration

Transformation methods

const nums = [4, 1, 8, 3];

nums.map(n => n * 2);          // [8, 2, 16, 6]  same length
nums.filter(n => n > 3);       // [4, 8]         subset
nums.find(n => n > 3);         // 4              first match
nums.findIndex(n => n > 3);    // 0
nums.reduce((t, n) => t + n, 0); // 16           collapse to one value
nums.some(n => n > 7);         // true
nums.every(n => n > 0);        // true

Looping choices

for (const item of nums) console.log(item);        // values
for (const [i, item] of nums.entries()) console.log(i, item);
nums.forEach(n => console.log(n));                 // no break/continue

// never use for...in for arrays - it walks enumerable keys
for (const k in nums) console.log(k); // '0','1',... plus inherited surprises

Useful patterns

const unique = [...new Set(arr)];
const flat = nested.flat(2);
const chunks = Array.from({ length: Math.ceil(a.length / 10) }, (_, i) => a.slice(i * 10, i * 10 + 10));
const grouped = Object.groupBy(items, x => x.type); // modern runtimes

// shallow copy vs mutation
const sorted = [...nums].sort((a, b) => a - b); // keeps nums intact

Full lesson: Arrays and iteration →

Objects and destructuring

Short modern syntax

const id = 7, active = true;
const user = { id, active };           // property shorthand
const user2 = { id, role: 'admin', login() { return this.id; } };

const { id: userId, role = 'guest' } = user2;  // rename + default
const copy = { ...user2, role: 'owner' };      // spread override

References and copies

const a = { tags: ['x'] };
const b = a;
b.tags.push('y');
console.log(a.tags); // ['x','y'] - same object

const shallow = { ...a };              // top level copied only
const deep = structuredClone(a);       // true deep copy (modern runtimes)

Object vs Map

const m = new Map();
m.set(user, 'cached');   // any key type
m.size;                  // no Object.keys length dance
for (const [k, v] of m) console.log(k, v);

Full lesson: Objects and destructuring →

Working with the DOM

Finding elements

document.querySelector('.card');          // first match
const all = document.querySelectorAll('.card'); // static NodeList
all.forEach(el => el.classList.add('seen'));

// cache a reference rather than re-querying in loops
const form = document.querySelector('#signup');

Reading and writing

el.textContent = userInput;          // rendered as plain text
el.setAttribute('aria-expanded', 'false');
el.dataset.userId = '42';            // data-user-id

// style: prefer classes over inline styles
el.classList.toggle('is-open', open);
el.style.setProperty('--accent', '#4f46e5');

Creating and inserting

const li = document.createElement('li');
li.className = 'row';
li.textContent = ' item ';
list.append(li);            // or prepend / before / after

// efficient bulk insert
const frag = document.createDocumentFragment();
items.forEach(i => frag.append(makeRow(i)));
list.append(frag);          // single reflow

li.remove();

Full lesson: Working with the DOM →

Events

Listening

btn.addEventListener('click', event => {
  console.log(event.target);   // what was clicked
  console.log(event.currentTarget); // where the listener lives
});

// remove requires the same function reference
function handler() {}
el.addEventListener('click', handler);
el.removeEventListener('click', handler);

Bubbling and capturing

el.addEventListener('click', fn);              // bubble (default)
el.addEventListener('click', fn, true);        // capture
el.addEventListener('click', fn, { once: true, passive: true });

event.stopPropagation();  // stop further travel
event.preventDefault();   // stop the default action

Event delegation

list.addEventListener('click', e => {
  const btn = e.target.closest('[data-action]');
  if (!btn) return;              // click was elsewhere
  handle(btn.dataset.action, btn.dataset.id);
});

Full lesson: Events →

Async JavaScript and fetch

fetch, properly

async function getJson(url) {
  const res = await fetch(url, {
    headers: { Accept: 'application/json' },
    credentials: 'same-origin'
  });
  if (!res.ok) {                       // fetch does NOT throw on 404/500
    throw new Error('HTTP ' + res.status);
  }
  return res.json();
}

fetch, properly

await fetch('/api/item', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'new' })
});

// timeouts with AbortController
const ac = new AbortController();
setTimeout(() => ac.abort(), 8000);
const res = await fetch(url, { signal: ac.signal });

Concurrency patterns

// sequential - each waits for the previous
for (const id of ids) results.push(await get(id));

// parallel - start all, wait for all
const results = await Promise.all(ids.map(get));

// tolerate individual failures
const settled = await Promise.allSettled(ids.map(get));
const ok = settled.filter(r => r.status === 'fulfilled').map(r => r.value);

// race: first to settle
const fastest = await Promise.any([fetch(a), fetch(b)]);

Full lesson: Async JavaScript and fetch →

Modules and project structure

Folders and package.json

src/
  main.js            entry point, wires things together
  api/client.js      one job: talk to the network
  ui/                components and their styles
  lib/               framework-free helpers
  config.js          env-derived settings
tests/               mirrors src/ structure

Full lesson: Modules and project structure →

Tooling: linting, formatting, bundling and testing

Linting and formatting

npx eslint . --fix        # report and fix what is safe
npx prettier --write .    # format every supported file
npx prettier --check .    # CI: fail on unformatted files
npx tsc --noEmit          # type-check without emitting files

Dev server, build and type checking

// vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
  server: { port: 5173, proxy: { '/api': 'http://localhost:8000' } },
  build: { outDir: 'dist', sourcemap: true, target: 'es2022' },
  define: { __APP_VERSION__: JSON.stringify(process.env.npm_package_version) },
});

Full lesson: Tooling: linting, formatting, bundling and testing →

FAQ

Is this JavaScript cheat sheet free to use?
Yes. No sign-up and no tracking: the page is static, every example is on the page itself, and you can print it or save it as a one-page reference.
Where do the examples come from?
Every snippet is taken from the 9 lessons of the JavaScript course on this site, and each section links back to the lesson it was pulled from.
How do I go deeper than a cheat sheet?
Open the full JavaScript course — it carries the worked explanations, the edge cases and the exercises behind every line here.

HTML CSS TypeScript HTML DOM AJAX JSON

Last refreshed 2026-09-27.