Skip to main content

JavaScript Cheatsheet

Languages 13 views Apr 2026

JavaScript Cheatsheet

Variables & Types

// Declaration
let x = 10;       // block-scoped, reassignable
const PI = 3.14;  // block-scoped, not reassignable
var old = 5;      // function-scoped (avoid)

// Types
typeof 42          // "number"
typeof "hello"     // "string"
typeof true        // "boolean"
typeof undefined   // "undefined"
typeof null        // "object" (historical quirk)
typeof {}          // "object"
typeof []          // "object"
typeof function(){} // "function"

// Type coercion
"5" + 3        // "53"  (string concat)
"5" - 3        // 2     (numeric sub)
"5" == 5       // true  (loose equality)
"5" === 5      // false (strict equality — always use this!)
Boolean(0)     // false
Boolean("")    // false
Boolean(null)  // false
Boolean(NaN)   // false
Boolean(undefined) // false

Strings

const s = "Hello, World!";

s.length            // 13
s.charAt(0)         // "H"
s.indexOf("World")  // 7
s.includes("World") // true
s.startsWith("He")  // true
s.endsWith("!")     // true
s.slice(7, 12)      // "World"
s.toUpperCase()     // "HELLO, WORLD!"
s.toLowerCase()     // "hello, world!"
s.trim()            // remove whitespace
s.replace("World","JS") // "Hello, JS!"
s.replaceAll("l","L")   // "HeLLo, WorLd!"
s.split(", ")       // ["Hello", "World!"]
s.padStart(15, "*") // "**Hello, World!"
s.padEnd(15, "*")   // "Hello, World!**"
s.repeat(2)         // "Hello, World!Hello, World!"

// Template literals
const name = "Alice";
const age = 30;
const msg = `${name} is ${age} years old`;

// Tagged template
const html = String.raw`<div class="\n"></div>`;

Arrays

const arr = [1, 2, 3, 4, 5];

// Mutating
arr.push(6)         // add to end → returns new length
arr.pop()           // remove from end → returns removed
arr.unshift(0)      // add to start
arr.shift()         // remove from start
arr.splice(1, 2)    // remove 2 items at index 1
arr.sort((a,b) => a-b)  // sort ascending
arr.reverse()

// Non-mutating (returns new array)
arr.slice(1, 3)         // [2,3]
arr.concat([6,7])       // [1,2,3,4,5,6,7]
arr.map(x => x * 2)     // [2,4,6,8,10]
arr.filter(x => x > 2)  // [3,4,5]
arr.reduce((acc,x) => acc+x, 0)  // 15
arr.flat()              // flatten 1 level
arr.flatMap(x => [x, x*2])       // map + flat
arr.find(x => x > 3)    // 4 (first match)
arr.findIndex(x => x>3) // 3
arr.some(x => x > 4)    // true
arr.every(x => x > 0)   // true
arr.includes(3)          // true
arr.indexOf(3)           // 2
arr.join(", ")           // "1, 2, 3, 4, 5"

// Spread & destructuring
const [a, b, ...rest] = arr;    // a=1,b=2,rest=[3,4,5]
const copy = [...arr];
const merged = [...arr, ...other];

// Array.from
Array.from("hello")             // ["h","e","l","l","o"]
Array.from({length:5}, (_,i)=>i) // [0,1,2,3,4]

Objects

const obj = { name: "Alice", age: 30, city: "NYC" };

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

// Shorthand
const x = 1, y = 2;
const point = { x, y };        // { x:1, y:2 }

// Spread & destructuring
const { name, age, ...rest } = obj;
const copy = { ...obj };
const merged = { ...obj, city: "LA" };

// Methods
Object.keys(obj)    // ["name","age","city"]
Object.values(obj)  // ["Alice",30,"NYC"]
Object.entries(obj) // [["name","Alice"],...]
Object.assign({}, obj, { age: 31 })
Object.freeze(obj)  // immutable
Object.fromEntries([["a",1],["b",2]])  // {a:1,b:2}

// Computed properties
const key = "dynamic";
const o = { [key]: 42 };  // { dynamic: 42 }

// Getter / Setter
const circle = {
  _r: 5,
  get area() { return Math.PI * this._r ** 2; },
  set radius(r) { this._r = r; }
};

Functions

// Declaration (hoisted)
function add(a, b) { return a + b; }

// Expression
const mul = function(a, b) { return a * b; };

// Arrow (no own this)
const sub = (a, b) => a - b;
const square = x => x ** 2;
const greet = () => "Hello!";

// Default params
function greet(name = "World") { return `Hello, ${name}!`; }

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

// Destructured params
function display({ name, age = 0 }) { return `${name}: ${age}`; }

// IIFE
(function() { console.log("runs immediately"); })();

// Closures
function counter() {
  let count = 0;
  return { inc: () => ++count, get: () => count };
}

Async / Promises

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

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

// Promise combinators
Promise.all([p1, p2, p3])        // all resolve or first reject
Promise.allSettled([p1, p2])     // all settle (resolve or reject)
Promise.race([p1, p2])           // first settled
Promise.any([p1, p2])            // first resolved

// async/await
async function fetchUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    return data;
  } catch (err) {
    console.error(err);
    throw err;
  }
}

// Parallel with await
const [user, posts] = await Promise.all([
  fetchUser(1),
  fetchPosts(1)
]);

// for-await (async iterables)
for await (const chunk of stream) {
  process(chunk);
}

Classes

class Animal {
  #name;   // private field (ES2022)

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

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

  get name() { return this.#name; }

  static create(name, sound) { return new Animal(name, sound); }
}

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

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

const d = new Dog("Rex");
d.speak();    // "Rex says Woof"
d.fetch("ball");

Modules (ES Modules)

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

// main.js
import Calculator, { PI, add } from "./math.js";
import * as math from "./math.js";

// Dynamic import (lazy load)
const { add } = await import("./math.js");

Useful Patterns

// Nullish coalescing
const val = maybeNull ?? "default";

// Logical assignment
x ||= "fallback";   // x = x || "fallback"
x &&= transform(x); // x = x && transform(x)
x ??= "default";    // x = x ?? "default"

// Optional chaining
user?.profile?.avatar?.url

// Proxy
const handler = {
  get(target, prop) { return prop in target ? target[prop] : 37; }
};
const p = new Proxy({}, handler);

// Symbol
const id = Symbol("id");
const obj = { [id]: 123 };

// WeakMap / WeakSet (GC-friendly)
const cache = new WeakMap();
cache.set(domNode, metadata);

Found this helpful? Share it!

Tweet LinkedIn WhatsApp
Translate Page