Skip to the content.

JavaScript Cheatsheet

JavaScript Cheatsheet

A quick reference guide for modern JavaScript (ES6+), async patterns, DOM manipulation, and essential web APIs.

Variables & Scope

// Scope declarations
const x = 10;               // Block-scoped, read-only constant (preferred)
let y = "hello";            // Block-scoped, re-assignable variable
var z = true;               // Function-scoped (legacy, avoid)

// Hoisting behavior
console.log(a);             // Throws ReferenceError (let/const are TDZ)
let a = 5;

console.log(b);             // Prints: undefined (var is hoisted but uninitialized)
var b = 5;

Modern ES6+ Syntax

// Arrow Functions
const add = (a, b) => a + b;
const getObj = () => ({ id: 1 });  // Implicit object return requires parentheses

// Destructuring Assignment
const user = { name: "Alice", age: 30, country: "US" };
const { name, age, city = "NY" } = user; // Extract with optional default value
const colors = ["red", "green", "blue"];
const [primary, secondary] = colors;    // Array destructuring

// Spread & Rest Operators
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];           // Spread: [1, 2, 3, 4]
const clone = { ...user, age: 31 };     // Object cloning & property override

const sumAll = (...args) => {           // Rest parameter: aggregates args into array
  return args.reduce((acc, val) => acc + val, 0);
};

// Optional Chaining & Nullish Coalescing
const street = user.address?.street;    // Safe access: returns undefined if address is null/undefined
const theme = user.theme ?? "dark";     // Falls back to "dark" ONLY if theme is null or undefined (not for "" or 0)
const legacy = user.theme || "dark";    // Falls back to "dark" for ANY falsy value ("", 0, false, null, undefined)

Promises & Async Flow

// Creating a Promise
const fetchData = (id) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) resolve({ id, data: "Success" });
      else reject(new Error("Invalid ID"));
    }, 1000);
  });
};

// Handling Promises (Chaining)
fetchData(1)
  .then(res => console.log(res))
  .catch(err => console.error(err.message))
  .finally(() => console.log("Done"));

// Async/Await (Modern standard)
async function handleFetch() {
  try {
    const res = await fetchData(1);
    console.log(res);
  } catch (err) {
    console.error(err.message);
  }
}

// Concurrent Promises
const [res1, res2] = await Promise.all([fetchData(1), fetchData(2)]);   // Parallel run (rejects if any fails)
const results = await Promise.allSettled([fetchData(1), fetchData(0)]); // Runs all, returns status & values

DOM Manipulation

// Selecting Elements
const el = document.getElementById("my-id");
const firstBtn = document.querySelector(".btn");          // First matching element
const allBtns = document.querySelectorAll(".btn-item");  // Returns non-live NodeList

// Modifying Content & Attributes
el.textContent = "Hello World";                           // Safe text injection (escaped)
el.innerHTML = "<strong>Hello</strong>";                  // Raw HTML injection (unsafe if from user input)
el.setAttribute("disabled", "true");
el.removeAttribute("disabled");

// Styling & Class List
el.style.backgroundColor = "var(--accent)";               // Inline CSS style override
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("selected");                          // Adds if missing, removes if present

// Creating & Appending Elements
const newDiv = document.createElement("div");
newDiv.className = "alert-box";
newDiv.textContent = "Data saved!";
document.body.appendChild(newDiv);                        // Adds to end of body

Event Listeners

// Basic listener
const button = document.querySelector("#submit-btn");
const handleClick = (event) => {
  console.log("Clicked!", event.target);
};
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);         // Requires named function reference to remove

// Event Delegation (Efficiently capture bubble events on dynamic list items)
const list = document.querySelector("#items-list");
list.addEventListener("click", (e) => {
  const item = e.target.closest(".list-item");
  if (item) {
    console.log("Clicked list item ID:", item.dataset.id);
  }
});

// Prevent defaults & propagation
form.addEventListener("submit", (e) => {
  e.preventDefault();                                     // Prevent page reload / submit action
  e.stopPropagation();                                    // Stop event from bubbling up DOM tree
});

Fetch API (HTTP Networking)

// GET Request
async function getJson(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    const data = await response.json();
    return data;
  } catch (err) {
    console.error("Fetch failed:", err);
  }
}

// POST Request with JSON Body
async function postData(url, payload) {
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(payload)
    });
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    return await response.json();
  } catch (err) {
    console.error("POST failed:", err);
  }
}

Web Storage

// LocalStorage (Persists indefinitely across browser sessions)
localStorage.setItem("theme", "dark");
const activeTheme = localStorage.getItem("theme");
localStorage.removeItem("theme");
localStorage.clear();

// SessionStorage (Cleared when the specific browser tab is closed)
sessionStorage.setItem("sessionId", "xyz123");
const session = sessionStorage.getItem("sessionId");

// Saving Complex Objects (Requires serialization)
const settings = { volume: 80, notifications: true };
localStorage.setItem("user-settings", JSON.stringify(settings));
const savedSettings = JSON.parse(localStorage.getItem("user-settings")) || {};

Utility Idioms & Helper Functions

// Checking data types safely
const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val);

// Deep Cloning (Structured Clone - modern browser standard)
const original = { a: 1, b: { c: 2 } };
const deepCopy = structuredClone(original);

// Basic Debounce Helper (Delays callback until time has elapsed since last call)
function debounce(func, delay = 300) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
}