Skip to main content
Quick Reference

JavaScript Cheatsheet

Complete modern JavaScript quick reference — variables, operators, strings, arrays, objects, functions, classes, async/await, DOM, modules, built-ins, ESNext syntax, and colorized snippets.

Variables & Types

let count = 0;          // reassignable
const PI = 3.14;         // cannot reassign
var legacy = "old";     // function-scoped — avoid

typeof 42;              // "number"
typeof null;             // "object" (legacy quirk)
Number.isNaN(x);
Array.isArray(arr);

// Primitive types: string, number, bigint, boolean, undefined, symbol, null
// Reference types: Object, Array, Function, Date, Map, Set, …
Keyword / checkNotes
letBlock-scoped, reassignable
constBlock-scoped, binding immutable (object contents can mutate)
varFunction-scoped, hoisted — prefer let/const
typeofReturns type string; typeof null === "object"
instanceofPrototype chain check for objects
Truthy / falsyFalsy: false, 0, -0, 0n, "", null, undefined, NaN

Operators

a + b;  a - b;  a * b;  a / b;  a % b;
a ** b;                 // exponentiation
a ++; a --;            // increment / decrement

a === b;  a !== b;   // strict equality (prefer)
a == b;                 // loose — coerces types

a && b;  a || b;  !a;
a ?? b;                   // nullish coalescing
obj?.prop?.method?.();  // optional chaining

cond ? yes : no;        // ternary
x += 1;  s += "!";
OperatorNotes
=== / !==Strict equality — no type coercion
== / !=Loose equality — avoid in most code
??Nullish coalescing — only null/undefined
?.Optional chaining — short-circuits to undefined
&& / ||Logical AND / OR (also used for short-circuit assign)
**Exponentiation
typeof / delete / void / inUnary / relational operators

Strings

const name = "Ada";
const msg = `Hello, ${name}!`;   // template literal
msg.length;  msg.toUpperCase();  msg.includes("Ada");
"a,b,c".split(",");
"  hi  ".trim();
"hello".slice(1, 4);     // "ell"
"hi".repeat(3);  "x".padStart(3, "0");
String(42);  42.toString(16);
MethodNotes
length, at(), charAt()Size / character access
includes, startsWith, endsWith, indexOfSearch
slice, substring, split, replace/replaceAllExtract / transform
trim, padStart, padEnd, repeatWhitespace / padding
toUpperCase / toLowerCaseCase
Template literalsBackticks + ${expr}; multiline

Arrays

const nums = [1, 2, 3];
nums.push(4);  nums.pop();
nums.unshift(0);  nums.shift();
nums.map(n => n * 2);
nums.filter(n => n % 2 === 0);
nums.reduce((a, n) => a + n, 0);
nums.find(n => n > 1);  nums.includes(2);
nums.slice(0, 2);  nums.splice(1, 1, 9);
[...nums, 5];               // spread copy / concat
const [first, ...rest] = nums;
MethodMutates?Notes
push / pop / shift / unshiftYesAdd/remove ends
spliceYesInsert/remove at index
sliceNoShallow copy / subarray
map / filter / reduceNoTransform / fold
find / findIndex / some / everyNoSearch / predicates
includes / indexOfNoMembership
sort / reverseYesIn-place; sort is lexicographic by default
flat / flatMap / concatNoFlatten / join
Array.from / Array.isArray—Create / type-check

Objects

const user = {
  id: 1,
  name: "Sam",
  greet() { return `Hi ${this.name}`; },
};

user.name;  user['name'];
const { name, id: uid } = user;  // destructure
const copy = { ...user, role: "admin" };
Object.keys(user);  Object.values(user);
Object.entries(user);
Object.assign({}, user);
APINotes
obj.key / obj["key"]Property access
Object.keys/values/entriesEnumerate own enumerable props
Object.assign / spread {...obj}Shallow merge / clone
Object.hasOwnOwn property check (prefer over hasOwnProperty)
Object.freeze / sealImmutability helpers (shallow)
Destructuringconst { a, b: alias } = obj

Functions

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

const mul = function(a, b) { return a * b; };
const div = (a, b) => a / b;
const sq = n => n ** 2;

// Rest + defaults
function sum(...nums) {
  return nums.reduce((a, n) => a + n, 0);
}

// IIFE
(function() { /* … */ })();
FormNotes
DeclarationHoisted; function name() {}
ExpressionNot hoisted as callable name
ArrowLexical this; no arguments; concise body
Default / restfn(a = 1, ...rest)
call / apply / bindSet this / partial apply
ClosuresInner function retains outer scope

Control Flow

if (x > 0) {
  // …
} else if (x < 0) {
  // …
} else {
  // …
}

switch (status) {
  case "ok": handleOk(); break;
  case "err": handleErr(); break;
  default: handleOther();
}

for (let i = 0; i < n; i++) { /* … */ }
for (const item of list) { /* … */ }
for (const key in obj) { /* … */ }
list.forEach(item => { /* … */ });

while (cond) { /* … */ }
do { /* … */ } while (cond);
try { /* … */ } catch (e) { /* … */ } finally { /* … */ }
ConstructNotes
if / elseConditional branches
switchStrict equality match; remember break
for / while / do…whileClassic loops
for…ofIterate values (iterables)
for…inEnumerate keys (use carefully on arrays)
break / continueExit / skip iteration
try / catch / finally / throwError handling

Classes & Prototypes

class Person {
  constructor(name) {
    this.name = name;
  }
  hello() {
    return `Hi, ${this.name}`;
  }
  static create(name) {
    return new Person(name);
  }
}

class Admin extends Person {
  hello() {
    return super.hello() + " (admin)";
  }
}

const p = new Admin("Sam");
p instanceof Person;  // true
FeatureNotes
class / extends / superSyntactic sugar over prototypes
constructorInit instance
staticOn the constructor, not instances
#privateTrue private fields/methods
instanceof / newInstance check / construct
Getters / settersget foo() / set foo(v)

Promises & Async

const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve("done"), 200);
});

p
  .then(v => console.log(v))
  .catch(e => console.error(e))
  .finally(() => {});

async function load() {
  try {
    const res = await fetch("/api");
    const data = await res.json();
    return data;
  } catch (e) {
    console.error(e);
  }
}

Promise.all([p1, p2]);
Promise.race([p1, p2]);
Promise.allSettled([p1, p2]);
APINotes
new Promiseresolve / reject executor
then / catch / finallyChain handlers
async / awaitSyntactic sugar over promises
Promise.allFail-fast parallel
Promise.allSettledWait for all outcomes
Promise.race / anyFirst settle / first fulfill
fetchNetwork requests → Response

DOM & Events

const el = document.querySelector(".btn");
document.querySelectorAll("li");
document.getElementById("app");

el.textContent = "Click";
el.classList.add("active");
el.setAttribute("aria-pressed", "true");
el.style.display = "block";

el.addEventListener("click", (e) => {
  e.preventDefault();
  console.log(e.target);
});

const node = document.createElement("div");
parent.append(node);  node.remove();
APINotes
querySelector / AllCSS selector queries
textContent / innerHTMLPrefer textContent when possible (XSS)
classListadd, remove, toggle, contains
addEventListenerPrefer over onclick attributes
createElement / append / removeBuild / tear down nodes
datasetRead/write data-* attributes

ES Modules

// math.js
export const PI = 3.14;
export function add(a, b) { return a + b; }
export default function main() { }

// app.js
import main, { add, PI } from "./math.js";
import * as math from "./math.js";
const mod = await import("./lazy.js");  // dynamic
SyntaxNotes
export / export defaultNamed vs default exports
import { x } fromNamed import
import * as nsNamespace import
import()Dynamic import → Promise
type="module"Enable ESM in browsers; deferred by default

Built-in Objects

JSON.stringify(obj);  JSON.parse(str);
Math.floor(3.7);  Math.random();  Math.max(...arr);
const d = new Date();  d.toISOString();
const map = new Map([["a", 1]]);
map.set("b", 2);  map.get("a");
const set = new Set([1, 2, 2]);  set.has(1);
setTimeout(fn, 1000);  clearTimeout(id);
localStorage.setItem("k", "v");  localStorage.getItem("k");
Built-inCommon use
JSONSerialize / parse data
MathNumeric helpers
DateTimestamps / formatting (prefer libraries for TZ-heavy work)
Map / SetKeyed collections / unique values
WeakMap / WeakSetWeakly held keys (GC-friendly)
localStorage / sessionStorageBrowser key-value storage (strings only)
IntlLocale-aware formatters

ESNext Patterns

// Destructuring & rest
const { a, b: bee, ...rest } = obj;
const [x, y = 0, ...more] = arr;

// Nullish / optional
const port = env.PORT ?? 3000;
const len = arr?.length ?? 0;

// Logical assignment
x ||= "default";  y &&= f();  z ??= 1;

// Private fields / static blocks (classes)
class Counter { #n = 0; inc() { this.#n++; } }

// Top-level await (modules), Array.at, Object.hasOwn, …
arr.at(-1);  Object.hasOwn(obj, "key");
FeatureNotes
DestructuringObjects & arrays; defaults; rest
SpreadCopy/merge arrays & objects
Nullish / optional??, ?.
Logical assignment||=, &&=, ??=
Private fields#name
Array.at / Object.hasOwnModern convenience APIs

Gotchas & Interview Tips

  • Prefer === over ==; know that typeof null === "object".
  • const prevents rebinding, not mutation — freeze or copy if needed.
  • Arrow functions do not bind their own this — do not use as methods that need instance this.
  • Array sort() mutates and sorts as strings by default — pass a compare fn for numbers.
  • Closures capture variables by reference — be careful in loops with var (use let).
  • Promises: always handle rejections; async functions always return a Promise.
  • innerHTML with user input is an XSS risk — prefer textContent or sanitization.
  • Event listeners: remove when components unmount; use event delegation for lists.

Next: JavaScript tutorial · Cheatsheet hub · HTML · CSS