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
| Topic | What it covers | |
|---|---|---|
| JavaScript basics | Everything else — arrays, functions, dates, regular expressions — is an object. This is why typeof null returning | lesson |
| Functions and scope | let and const are block-scoped; var is function-scoped. A closure is simply a function that keeps access to variables | lesson |
| Arrays and iteration | The methods that replace most for-loops — map, filter, reduce, find — and when mutation versus copying matters | lesson |
| Objects and destructuring | Objects are copied by reference: assigning one does not clone it, so both variables point at the same data | lesson |
| Working with the DOM | querySelectorAll returns a static NodeList; getElementsByClassName returns a live HTMLCollection that updates as the | lesson |
| Events | An event travels three phases: capture down from the root, the target, then bubble back up. Listeners default to the | lesson |
| Async JavaScript and fetch | A promise is a placeholder for a value that is not ready yet. It settles once — either fulfilled with a value, or | lesson |
| Modules and project structure | An ES module has its own scope, is always strict, and runs once no matter how many times it is imported. Imports are | lesson |
| Tooling: linting, formatting, bundling and testing | Prettier decides layout — indentation, quotes, line breaks — and never argues about meaning. ESLint finds likely bugs | lesson |
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 intactFull 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);
});
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/ structureFull 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?
Where do the examples come from?
How do I go deeper than a cheat sheet?
Related cheat sheets
HTML CSS TypeScript HTML DOM AJAX JSON
Last refreshed 2026-09-27.