JavaScript Cheat Sheet

Modern JavaScript (ES6+) quick reference. Variables, data types, arrays, objects, functions, DOM, async/await, classes, and more.

Variables & Types

SyntaxDescription
const x = 1Block-scoped constant (cannot be reassigned)
let y = 2Block-scoped variable (can be reassigned)
var z = 3Function-scoped variable (avoid — use let/const)

Data Types

TypeExampleCheck
String"hello" 'hi' `template`typeof x === "string"
Number42 3.14 NaN Infinitytypeof x === "number"
BigInt9007199254740991ntypeof x === "bigint"
Booleantrue falsetypeof x === "boolean"
nullnullx === null
undefinedundefinedtypeof x === "undefined"
SymbolSymbol("id")typeof x === "symbol"
Object{} [] new Date()typeof x === "object"

Type Conversion

String(123)          // "123"
Number("42")         // 42
Number("abc")        // NaN
Boolean(0)           // false
Boolean("")          // false
Boolean(null)        // false
Boolean("hello")     // true
parseInt("42px")     // 42
parseFloat("3.14")   // 3.14
+"42"                // 42 (unary plus shorthand)

Strings

Method / SyntaxDescription
`Hello ${name}`Template literal (interpolation)
str.lengthString length
str.includes("abc")Check if string contains substring
str.startsWith("He")Check if starts with
str.endsWith("lo")Check if ends with
str.indexOf("l")First index of substring (-1 if not found)
str.slice(0, 5)Extract substring (start, end)
str.substring(0, 5)Extract substring (no negative indices)
str.replace("a", "b")Replace first occurrence
str.replaceAll("a", "b")Replace all occurrences
str.split(",")Split into array
str.trim()Remove whitespace from both ends
str.trimStart()Remove whitespace from start
str.toUpperCase()Convert to uppercase
str.toLowerCase()Convert to lowercase
str.padStart(5, "0")Pad start to length 5 with "0"
str.repeat(3)Repeat string 3 times
str.match(/regex/g)Find all regex matches
str.at(-1)Last character (ES2022)

Arrays

Create & Access

const arr = [1, 2, 3];
arr[0]           // 1
arr.at(-1)        // 3 (last element)
arr.length        // 3
Array.isArray(arr) // true
Array.from("abc") // ["a", "b", "c"]
Array(5).fill(0)  // [0, 0, 0, 0, 0]

Mutating Methods

MethodDescription
push(item)Add to end, return new length
pop()Remove from end, return removed item
unshift(item)Add to beginning
shift()Remove from beginning
splice(i, n, ...items)Remove n items at index i, insert items
sort()Sort in place (lexicographic by default)
sort((a,b) => a - b)Sort numbers ascending
reverse()Reverse in place
fill(value, start, end)Fill with value

Non-Mutating Methods

MethodDescription
map(fn)Transform each element, return new array
filter(fn)Keep elements where fn returns true
reduce(fn, init)Accumulate into single value
find(fn)First element where fn returns true
findIndex(fn)Index of first match (-1 if none)
some(fn)True if any element passes test
every(fn)True if all elements pass test
includes(val)True if array contains value
indexOf(val)First index of value (-1 if not found)
forEach(fn)Execute fn for each element (no return)
concat(arr2)Merge arrays into new array
slice(start, end)Extract portion into new array
flat(depth)Flatten nested arrays
flatMap(fn)Map then flatten one level
join(sep)Join elements into string
toSorted(fn)Sort without mutating (ES2023)
toReversed()Reverse without mutating (ES2023)
// Common patterns
[1,2,3].map(x => x * 2)              // [2, 4, 6]
[1,2,3,4].filter(x => x > 2)           // [3, 4]
[1,2,3].reduce((sum, x) => sum + x, 0) // 6
[1,2,3].find(x => x > 1)               // 2
[...new Set([1,1,2,3])]                 // [1, 2, 3] (dedupe)

Objects

// Create
const obj = { name: "Alice", age: 30 };

// Access
obj.name              // "Alice"
obj["name"]           // "Alice"
obj?.address?.city    // undefined (optional chaining)

// Modify
obj.email = "a@b.com";  // add property
delete obj.age;          // remove property
MethodDescription
Object.keys(obj)Array of keys
Object.values(obj)Array of values
Object.entries(obj)Array of [key, value] pairs
Object.assign(target, src)Copy properties (shallow)
Object.freeze(obj)Prevent modifications
Object.fromEntries(arr)Create object from [key, value] pairs
"key" in objCheck if key exists
obj.hasOwnProperty("key")Check own property (not inherited)
{...obj, newKey: val}Spread into new object (shallow copy + add)
structuredClone(obj)Deep clone (ES2022)

Map & Set

// Map — key-value pairs (any key type)
const map = new Map();
map.set("key", "value");
map.get("key");        // "value"
map.has("key");        // true
map.delete("key");
map.size;              // 0

// Set — unique values
const set = new Set([1, 2, 2, 3]);
set.add(4);
set.has(2);            // true
set.delete(2);
set.size;              // 3
[...set]               // [1, 3, 4]

Functions

// Function declaration
function add(a, b) { return a + b; }

// Function expression
const add = function(a, b) { return a + b; };

// Arrow function
const add = (a, b) => a + b;
const greet = name => `Hello, ${name}!`;
const getObj = () => ({ key: "value" }); // return object

// Default parameters
function greet(name = "World") { return `Hi ${name}`; }

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

// IIFE (Immediately Invoked)
(() => { console.log("runs now"); })();
Tip: Arrow functions don't have their own this — they inherit it from the enclosing scope. Use regular functions for object methods and class methods.

Destructuring & Spread

// Array destructuring
const [a, b, ...rest] = [1, 2, 3, 4];
// a=1, b=2, rest=[3,4]

// Object destructuring
const { name, age, city = "NYC" } = person;
const { name: fullName } = person;  // rename

// Nested destructuring
const { address: { city } } = person;

// Spread operator
const arr2 = [...arr1, 4, 5];       // array spread
const obj2 = { ...obj1, key: "val" }; // object spread

// Function argument destructuring
function greet({ name, age }) {
  return `${name} is ${age}`;
}

Control Flow

// Ternary
const status = age >= 18 ? "adult" : "minor";

// Nullish coalescing (??) — null/undefined only
const val = input ?? "default";

// Logical OR (||) — any falsy value
const val = input || "default";

// Logical AND (&&) — short circuit
isValid && doSomething();

// Optional chaining
user?.address?.city
arr?.[0]
fn?.()

// for...of (iterables: arrays, strings, maps, sets)
for (const item of array) { }

// for...in (object keys)
for (const key in object) { }

// Switch
switch (action) {
  case "start": start(); break;
  case "stop":  stop();  break;
  default: idle();
}

// try/catch/finally
try {
  riskyOperation();
} catch (err) {
  console.error(err.message);
} finally {
  cleanup();
}

DOM Manipulation

MethodDescription
document.getElementById("id")Select by ID
document.querySelector(".class")Select first match (CSS selector)
document.querySelectorAll("p")Select all matches (NodeList)
el.textContent = "text"Set text content
el.innerHTML = "<b>html</b>"Set HTML content
el.setAttribute("href", url)Set attribute
el.getAttribute("href")Get attribute
el.classList.add("active")Add CSS class
el.classList.remove("active")Remove CSS class
el.classList.toggle("active")Toggle CSS class
el.classList.contains("active")Check if class exists
el.style.color = "red"Set inline style
document.createElement("div")Create element
parent.appendChild(child)Append child element
parent.removeChild(child)Remove child element
el.remove()Remove element from DOM
el.closest(".class")Find nearest ancestor matching selector

Events

el.addEventListener("click", (e) => {
  e.preventDefault();     // prevent default behavior
  e.stopPropagation();    // stop event bubbling
  e.target                // element that triggered event
  e.currentTarget         // element listener is attached to
});

// Common events: click, submit, input, change,
// keydown, keyup, mouseover, mouseout, scroll,
// load, DOMContentLoaded, resize, focus, blur

// Event delegation
document.querySelector("ul").addEventListener("click", (e) => {
  if (e.target.matches("li")) {
    handleClick(e.target);
  }
});

Async / Promises

// Promise
const p = new Promise((resolve, reject) => {
  // async work...
  resolve("done");   // or reject(new Error("fail"))
});

p.then(val => console.log(val))
 .catch(err => console.error(err))
 .finally(() => cleanup());

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

// Parallel execution
const [a, b] = await Promise.all([fetchA(), fetchB()]);

// Race — first to settle wins
const result = await Promise.race([fetchA(), timeout(5000)]);

// allSettled — wait for all, never rejects
const results = await Promise.allSettled([p1, p2, p3]);

Fetch API

// GET
const res = await fetch("/api/users");
const users = await res.json();

// POST
const res = await fetch("/api/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Alice" }),
});

// Check response
if (!res.ok) throw new Error(`HTTP ${res.status}`);

Classes

class Animal {
  // Private field
  #sound;

  constructor(name, sound) {
    this.name = name;
    this.#sound = sound;
  }

  // Method
  speak() {
    return `${this.name} says ${this.#sound}`;
  }

  // Getter
  get info() { return `${this.name}`; }

  // Static method
  static create(name) { return new Animal(name, "..."); }
}

// Inheritance
class Dog extends Animal {
  constructor(name) {
    super(name, "Woof");
  }

  fetch(item) {
    return `${this.name} fetches ${item}`;
  }
}

Modules

// Named export
export const PI = 3.14;
export function add(a, b) { return a + b; }

// Default export
export default class App { }

// Named import
import { PI, add } from "./math.js";

// Default import
import App from "./App.js";

// Rename import
import { add as sum } from "./math.js";

// Import all
import * as math from "./math.js";

// Dynamic import
const module = await import("./heavy.js");

Useful Patterns

// Debounce
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

// Sleep / delay
const sleep = ms => new Promise(r => setTimeout(r, ms));
await sleep(1000);

// Random integer between min and max (inclusive)
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

// Shuffle array
arr.sort(() => Math.random() - 0.5);

// Group by
const grouped = Object.groupBy(items, item => item.category); // ES2024

// Remove duplicates
[...new Set(arr)]

// Check empty object
Object.keys(obj).length === 0

// JSON
JSON.stringify(obj)          // object → string
JSON.stringify(obj, null, 2) // pretty print
JSON.parse(str)              // string → object