JavaScript Cheat Sheet

Useful JavaScript syntax and APIs.

Variables and functions

const pi = 3.14;            // cannot be reassigned
let count = 0;              // block-scoped, reassignable
function add(a, b = 0) { return a + b; }   // default parameter
const square = x => x * x;                 // arrow function
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);  // rest

Destructuring, spread, optional chaining

const { name, age = 0, ...rest } = user;
const [first, , third] = list;
const merged = { ...defaults, ...options };
const copy = [...arr, 4];
const city = user?.address?.city ?? 'unknown';   // ?. and ??

Array methods

MethodReturnsExample
map(fn)New array[1,2].map(x => x * 2) → [2, 4]
filter(fn)New arraynums.filter(n => n > 0)
reduce(fn, init)One valuenums.reduce((s, n) => s + n, 0)
find(fn) / findIndex(fn)Item / indexusers.find(u => u.id === 7)
some(fn) / every(fn)Booleanarr.some(x => x == null)
includes(v)Boolean['a','b'].includes('a')
flat() / flatMap(fn)New array[[1],[2]].flat() → [1, 2]
sort((a, b) => a - b)Same array, sortedWithout a comparator, numbers sort as strings
toSorted(), toReversed()New arrayNon-mutating versions (ES2023)
at(-1)ItemLast element

Strings

`Hello ${name}`                 // template literal
s.trim()  s.toUpperCase()  s.padStart(5, '0')
s.split(',')  s.slice(0, 3)  s.replaceAll('a', 'b')
s.startsWith('http')  s.includes('@')

Objects and classes

Object.keys(o)  Object.values(o)  Object.entries(o)
Object.fromEntries([['a', 1]])         // { a: 1 }
structuredClone(o)                     // deep copy
class Point {
  #secret = 1;                         // private field
  constructor(x, y) { this.x = x; this.y = y; }
  get length() { return Math.hypot(this.x, this.y); }
  static origin() { return new Point(0, 0); }
}

Promises and async/await

async function load(url) {
  try {
    const res = await fetch(url);
    if (!res.ok) throw new Error(res.status);
    return await res.json();
  } catch (err) { console.error(err); }
}
const [a, b] = await Promise.all([load(u1), load(u2)]);

Gotchas

FAQ

let, const or var?

Use const by default, let when the variable is reassigned, and avoid var, which is function-scoped and hoisted.

How do I check my code for syntax errors?

Paste it into the JavaScript syntax checker, which reports the engine's error without running the code.