Tutorials JavaScript JS Cheat Sheet
Ch 78 / 78
Chapter 78 Beginner–Advanced 10 min read JavaScript

JavaScript Cheat Sheet — Complete Quick Reference

Your one-stop reference for every major JavaScript concept — variables, data types, functions, arrays, objects, classes, ES6+, async/await, DOM, regex, and more. Bookmark it, print it, download it as PDF.

What's in this cheat sheet
Variables, data types & operators
Functions, arrow functions & closures
Arrays, objects & destructuring
ES6+ features — spread, rest, optional chaining
Promises, async/await & Fetch API
DOM manipulation & events
Classes, prototypes & error handling
Regular expressions & built-in methods

📥 Download Cheat Sheet as PDF

Print-ready A4 layout — all syntax on one page. Updated for ES2025.

Download PDF

Variables & Declarations

Three ways to declare variables — each with different scoping rules and mutability.

var / let / const
var   x = 10;        // function-scoped, hoisted, re-declarable
let   y = 20;        // block-scoped, not re-declarable in same scope
const z = 30;        // block-scoped, cannot be reassigned

// Scope comparison
if (true) {
  var   a = "var";    // accessible outside block ⚠️
  let   b = "let";    // block-only ✓
  const c = "const";  // block-only ✓
}

// const with objects/arrays — reference is fixed, contents are mutable
const arr = [1, 2, 3];
arr.push(4);             // ✓ ok — contents changed
// arr = [];             // ✗ TypeError — can't reassign
Keyword Scope Hoisted Re-assignable Re-declarable
var Function ✓ (undefined) ✓ ✓
let Block ✗ (TDZ) ✓ ✗
const Block ✗ (TDZ) ✗ ✗

Data Types

JavaScript has 8 data types — 7 primitives and 1 object type.

Primitives
typeof "hello"     // "string"
typeof 42          // "number"
typeof 3.14n       // "bigint"
typeof true        // "boolean"
typeof undefined   // "undefined"
typeof null        // "object" ⚠️ legacy bug
typeof Symbol()    // "symbol"
typeof {}          // "object"
Type Conversion
Number("42")       // 42
Number("abc")      // NaN
String(99)         // "99"
Boolean(0)         // false
Boolean("")        // false
Boolean("hi")      // true
parseInt("10px")   // 10
parseFloat("3.5") // 3.5
Truthy / Falsy
// Falsy values (6 total):
false, 0, "", '', null, undefined, NaN

// Everything else is truthy:
"0"  // truthy  ✓
[]   // truthy  ✓
{}   // truthy  ✓
-1  // truthy  ✓
Template Literals
const name = "JS";
const msg = `Hello ${name}!`;

// Multi-line
const html = `
  <div>
    <p>${msg}</p>
  </div>
`;

// Tagged template
fn`Hello ${name}`;

Operators

Comparison & Logical
// Equality
5 == "5"   // true  — abstract equality (coerces types)
5 === "5"  // false — strict equality (no coercion) ✓ prefer this
5 !== "5"  // true

// Logical
true && false   // false  — AND
true || false   // true   — OR
!true            // false  — NOT

// Nullish coalescing (ES2020)
null ?? "default"       // "default"
0    ?? "default"       // 0  (only null/undefined triggers fallback)

// Optional chaining (ES2020)
user?.address?.city    // undefined instead of TypeError
arr?.[0]                // safe index
fn?.()                  // safe call

// Short-circuit assignment (ES2021)
a ||= b   // a = a || b
a &&= b   // a = a && b
a ??= b   // a = a ?? b
Advertisement

Functions

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

// Expression (not hoisted)
const multiply = function(a, b) {
  return a * b;
};

// Default params
function greet(name = "World") {
  return `Hi ${name}!`;
}
Arrow Functions
// Full
const add = (a, b) => { return a + b; };

// Implicit return (one-liner)
const add = (a, b) => a + b;

// Single param (no parens needed)
const double = n => n * 2;

// Return an object literal
const obj = () => ({ key: "val" });

// No own `this` — uses lexical this
Rest & Spread
// Rest — collect extra args
function sum(...nums) {
  return nums.reduce((a,b) => a+b, 0);
}
sum(1,2,3);   // 6

// Spread — expand iterable
const a = [1,2];
const b = [3,4];
const c = [...a, ...b];  // [1,2,3,4]

Math.max(...a);           // 2
Closures & IIFE
// Closure: inner fn remembers outer scope
function counter() {
  let count = 0;
  return () => ++count;
}
const inc = counter();
inc(); inc();  // 1, 2

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

Arrays & Array Methods

Array Methods Cheat Sheet
const nums = [1, 2, 3, 4, 5];

// ── Mutation ───────────────────────────────────────────────────
nums.push(6);             // add to end   → [1,2,3,4,5,6]
nums.pop();               // remove end   → returns 6
nums.unshift(0);          // add to start → [0,1,2,3,4,5]
nums.shift();             // remove start → returns 0
nums.splice(1, 2);        // remove 2 from index 1
nums.splice(1, 0, 99);   // insert 99 at index 1
nums.sort();              // lexicographic sort (mutates!)
nums.sort((a,b) => a-b);   // numeric ascending
nums.reverse();           // reverse in place
nums.fill(0, 2, 4);       // fill [0,0] from idx 2 to 4

// ── Non-mutation ───────────────────────────────────────────────
nums.slice(1, 3);         // [2,3] — copy portion
nums.concat([6,7]);       // joins arrays
nums.flat(2);             // flattens 2 levels deep
nums.flatMap(x => [x, x*2]); // map + flat(1)
[...[1], ...[2]];          // spread clone/merge

// ── Iteration ──────────────────────────────────────────────────
nums.forEach(n => console.log(n));     // iterate
nums.map(n => n * 2);                 // [2,4,6,8,10]
nums.filter(n => n > 2);              // [3,4,5]
nums.reduce((acc, n) => acc+n, 0);   // 15
nums.find(n => n > 3);               // 4
nums.findIndex(n => n > 3);         // 3
nums.some(n => n > 4);               // true
nums.every(n => n > 0);              // true
nums.includes(3);                  // true
nums.indexOf(3);                   // 2
nums.join(", ");                    // "1, 2, 3, 4, 5"

// ── Creation ───────────────────────────────────────────────────
Array.from("abc");          // ["a","b","c"]
Array.from({length:3}, (_,i) => i); // [0,1,2]
Array.of(1,2,3);             // [1,2,3]
Array.isArray([]);           // true

Destructuring

Array Destructuring
const [a, b, c] = [1, 2, 3];

// Skip items
const [first, , third] = [1, 2, 3];

// Default values
const [x = 0, y = 0] = [10];

// Rest
const [head, ...tail] = [1, 2, 3];

// Swap
[a, b] = [b, a];
Object Destructuring
const { name, age } = user;

// Rename
const { name: n, age: a } = user;

// Default values
const { city = "Vadodara" } = user;

// Nested
const { address: { zip } } = user;

// Rest
const { name, ...rest } = user;

// In function params
function show({ name, age = 18 }) {…}
⚡
Free Resource
Download our JavaScript Interview Prep Sheet
Top 50 JS interview questions with detailed answers — all in one page.
View Now

Objects

Object Syntax & Methods
// Creation
const obj = { name: "JS", version: 2025 };

// Shorthand property (ES6)
const name = "JS";
const o = { name };      // { name: "JS" }

// Computed property keys
const key = "foo";
const p = { [key]: 42 }; // { foo: 42 }

// Spread / merge objects
const merged = { ...objA, ...objB };

// Built-in static methods
Object.keys(obj)          // ["name","version"]
Object.values(obj)        // ["JS",2025]
Object.entries(obj)       // [["name","JS"],["version",2025]]
Object.assign({}, obj)    // shallow copy
Object.freeze(obj)        // makes immutable
Object.fromEntries(map)   // Map → object
Object.hasOwn(obj, "name") // true (ES2022)

// Property descriptors
Object.defineProperty(obj, "id", {
  value: 1, writable: false, enumerable: true
});

Classes & Prototypes

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

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

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

  static kingdom() { return "Animalia"; }  // static method

  get name()    { return this.#name; }       // getter
  set name(val) { this.#name = val; }        // setter
}

class Dog extends Animal {
  constructor(name) {
    super(name, "Woof");
    this.tricks = [];
  }

  learn(trick) { this.tricks.push(trick); }
}

const d = new Dog("Rex");
d.speak();                  // "Rex says Woof"
d instanceof Dog;          // true
d instanceof Animal;       // true

Async JavaScript

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

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

Promise.all([p1, p2])      // all resolve
Promise.allSettled([p1,p2])// all settle
Promise.race([p1, p2])     // first wins
Promise.any([p1, p2])      // first fulfilled
async / await
async function getData() {
  try {
    const res = await fetch("/api/data");
    const data = await res.json();
    return data;
  } catch (err) {
    console.error(err);
  }
}

// Parallel calls
const [a, b] = await Promise.all([
  fetch("/api/a").then(r => r.json()),
  fetch("/api/b").then(r => r.json())
]);
Fetch API
// GET
const res = await fetch("/api/users");
const data = await res.json();

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

// Check status
if (!res.ok) throw new Error(res.statusText);
Error Handling
try {
  riskyOperation();
} catch (err) {
  console.error(err.message);
} finally {
  cleanup();
}

// Custom errors
class ApiError extends Error {
  constructor(msg, code) {
    super(msg);
    this.code = code;
  }
}
throw new ApiError("Not found", 404);
Advertisement

DOM Manipulation

Select · Create · Modify · Events
// ── Selecting ─────────────────────────────────────────────────
document.getElementById("id")
document.querySelector(".class")
document.querySelectorAll("p")
document.getElementsByClassName("cls")
el.closest(".parent")
el.matches(":hover")

// ── Creating ──────────────────────────────────────────────────
const div = document.createElement("div");
div.textContent = "Hello";
document.body.appendChild(div);
parent.insertBefore(div, refNode);
div.remove();
parent.replaceChild(newEl, oldEl);

// ── Content ───────────────────────────────────────────────────
el.textContent = "Safe text";         // safe — no HTML parsed
el.innerHTML   = "<b>Bold</b>";        // ⚠️ XSS risk
el.outerHTML;                            // element + self

// ── Attributes ───────────────────────────────────────────────
el.setAttribute("href", "/");
el.getAttribute("href");
el.removeAttribute("hidden");
el.dataset.userId;                       // data-user-id attribute

// ── Classes / Style ──────────────────────────────────────────
el.classList.add("active");
el.classList.remove("active");
el.classList.toggle("open");
el.classList.contains("open");
el.style.color = "red";
getComputedStyle(el).fontSize;

// ── Events ────────────────────────────────────────────────────
el.addEventListener("click", handler);
el.removeEventListener("click", handler);
function handler(e) {
  e.preventDefault();    // stop default behaviour
  e.stopPropagation();   // stop bubble
  e.target;              // element that was clicked
  e.currentTarget;       // element with listener
}

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

String Methods

Method What it does Example → Result
.length Character count (property) "hello".length → 5
.toUpperCase() All caps "js".toUpperCase() → "JS"
.toLowerCase() All lowercase "JS".toLowerCase() → "js"
.trim() Strip whitespace from both ends " hi ".trim() → "hi"
.trimStart() / .trimEnd() Strip one end only " hi ".trimStart() → "hi "
.includes(s) Boolean substring check "hello".includes("ell") → true
.startsWith(s) / .endsWith(s) Check prefix/suffix "hello".startsWith("he") → true
.indexOf(s) / .lastIndexOf(s) Find first/last position "abab".indexOf("b") → 1
.slice(s, e) Extract substring (negative ok) "hello".slice(1,3) → "el"
.substring(s, e) Like slice but no negatives "hello".substring(1,3) → "el"
.split(sep) String → array "a,b,c".split(",") → ["a","b","c"]
.replace(s, r) Replace first match "aaa".replace("a","b") → "baa"
.replaceAll(s, r) Replace all matches "aaa".replaceAll("a","b") → "bbb"
.repeat(n) Repeat string n times "ab".repeat(3) → "ababab"
.padStart(n, s) / .padEnd(n, s) Pad to length "5".padStart(3,"0") → "005"
.at(i) Index (negative ok) "hello".at(-1) → "o"
.match(rx) / .matchAll(rx) Regex match(es) "js2025".match(/\d+/) → ["2025"]
.search(rx) Regex index or -1 "hello".search(/l/) → 2
String.raw`…` Raw string (no escape) String.raw`\n` → "\\n"

Numbers & Math

Number Methods
(3.14159).toFixed(2)  // "3.14"
(1000).toLocaleString()  // "1,000"
Number.isNaN(NaN)         // true
Number.isFinite(Infinity) // false
Number.isInteger(3.0)     // true
Number.MAX_SAFE_INTEGER    // 9007199254740991
Number.EPSILON             // 2.22e-16
Math Object
Math.round(4.5)    // 5
Math.floor(4.9)    // 4
Math.ceil(4.1)     // 5
Math.abs(-7)       // 7
Math.max(1,5,3)    // 5
Math.min(1,5,3)    // 1
Math.pow(2,10)     // 1024
Math.sqrt(25)      // 5
Math.random()      // 0 ≤ n < 1
Math.trunc(4.9)    // 4 (drops decimal)
Math.PI            // 3.14159…

ES6+ Quick Reference

Feature ES Version Example
let / const ES6 (2015) let x = 1; const Y = 2;
Arrow functions ES6 const f = x => x * 2;
Template literals ES6 `Hello ${name}`
Destructuring ES6 const { a, b } = obj;
Default params ES6 function f(x = 0) {}
Spread / Rest ES6 [...arr]; function f(...args)
Modules (import/export) ES6 import { fn } from './mod.js';
Promise ES6 new Promise((res, rej) => …)
Map / Set / WeakMap ES6 new Map(); new Set([1,2]);
Symbol ES6 const s = Symbol("id");
Generators ES6 function* gen() { yield 1; }
Object.assign ES6 Object.assign({}, a, b);
Array.from ES6 Array.from("abc") // ["a","b","c"]
async / await ES8 (2017) const data = await fetch(url);
Object.entries/values ES8 Object.entries(obj)
Optional chaining (?.) ES11 (2020) user?.address?.city
Nullish coalescing (??) ES11 val ?? "default"
Promise.allSettled ES11 Promise.allSettled([p1, p2])
Logical assignment (&&=, ||=, ??=) ES12 (2021) a ??= "default";
Private class fields (#) ES13 (2022) class C { #x = 0; }
Array .at() / String .at() ES13 arr.at(-1);
Object.hasOwn ES13 Object.hasOwn(obj, "key")
Array .toSorted() .toReversed() ES14 (2023) arr.toSorted(fn) // non-mutating
Array.fromAsync ES2024 Array.fromAsync(asyncIterable)

Regular Expressions

Regex Syntax & Flags
// Create
const rx1 = /pattern/flags;         // literal
const rx2 = new RegExp("pattern", "g"); // dynamic

// Common flags
// g  — global (find all)
// i  — case-insensitive
// m  — multiline (^ and $ match lines)
// s  — dotAll (. matches \n)

// ── Character classes ─────────────────────────────────────────
// .     any char except newline
// \d    digit [0-9]          \D non-digit
// \w    word char [a-zA-Z0-9_]  \W non-word
// \s    whitespace           \S non-whitespace
// [abc] any of a, b, c       [^abc] none of a, b, c

// ── Quantifiers ───────────────────────────────────────────────
// *     0 or more       *? lazy
// +     1 or more       +? lazy
// ?     0 or 1          {n} exactly n   {n,m} range

// ── Anchors ───────────────────────────────────────────────────
// ^  start   $  end   \b word boundary

// ── Groups ────────────────────────────────────────────────────
// (abc)   capture group  — $1 / \1
// (?<name>abc)  named capture — groups.name
// (?:abc) non-capture group
// a(?=b)  lookahead  a(?!b) negative lookahead

// ── Methods ───────────────────────────────────────────────────
/\d+/.test("abc123")             // true
"a1b2".match(/\d/g)              // ["1","2"]
"hello".replace(/l/g, "r")       // "herro"
"a b".split(/\s+/)               // ["a","b"]
[..."a1b2".matchAll(/(\d)/g)]     // iterator of matches

Modules (import / export)

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

// Re-export
export { add as sum } from "./math.js";
export * from "./math.js";
Import Syntax
import Calculator from "./math.js";   // default
import { PI, add } from "./math.js"; // named
import * as Math from "./math.js";  // namespace
import { add as sum } from "./math.js"; // alias

// Dynamic import (lazy-load)
const mod = await import("./math.js");
mod.add(1, 2);

Web Storage, JSON & Timers

localStorage
localStorage.setItem("key", "val");
localStorage.getItem("key");      // "val"
localStorage.removeItem("key");
localStorage.clear();

// Store objects (JSON)
localStorage.setItem("user",
  JSON.stringify({ name: "K2" })
);
const u = JSON.parse(
  localStorage.getItem("user")
);
JSON
JSON.stringify(obj)          // → string
JSON.stringify(obj, null, 2) // pretty print
JSON.parse(str)              // → object

// Safe parse
function safeParse(s) {
  try { return JSON.parse(s); }
  catch { return null; }
}

// JSON rules:
// keys must be quoted
// no functions, undefined, Symbols
Timers
// Run once after delay
const id = setTimeout(() => {
  console.log("delayed");
}, 1000);
clearTimeout(id);

// Run repeatedly
const iv = setInterval(() => {
  console.log("tick");
}, 500);
clearInterval(iv);

// requestAnimationFrame
requestAnimationFrame(animate);
Map & Set
// Map — key/value, any key type
const m = new Map();
m.set("key", 42);
m.get("key");  // 42
m.has("key");  // true
m.size;         // 1
for (const [k,v] of m) { }

// Set — unique values
const s = new Set([1,2,2,3]);
s.add(4); s.delete(1);
[...s];          // [2,3,4]
// Deduplicate array:
[...new Set(arr)];
Quick Check — Chapter 78

Which method creates a new array with elements that pass a test function?

Try It — Practice Pad

Live Editor
✎ Editor
👁 Preview
Cheat Sheet Summary
  • Use const by default, let when you need to reassign, avoid var.
  • Strict equality (===) is always preferred over abstract equality (==).
  • Arrow functions are concise and use lexical this — ideal for callbacks.
  • Destructuring, spread, and rest are the ES6 trio that cleans up every codebase.
  • Use async/await over raw Promises for readability; always wrap in try/catch.
  • Optional chaining (?.) and nullish coalescing (??) eliminate most null-check boilerplate.
  • Array methods like map, filter, reduce enable clean functional pipelines.
  • This cheat sheet covers all 78 chapters — you have completed the JavaScript tutorial! 🎉

🎉 You finished the JS Tutorial!

Download the cheat sheet PDF as a permanent quick-reference companion.

Download PDF

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel