Back to roadmaps vanilla-js Course

JavaScript Cheat Sheet

A quick-reference dashboard for commonly used JavaScript APIs, signatures, and patterns. Bookmark this page for daily development reference.

1. Variables & Types

let count = 10;        // Reassignable block-scoped variable
const limit = 100;     // Non-reassignable constant

// Check data type
typeof "Hello";        // "string"
typeof 42;             // "number"
typeof true;           // "boolean"
typeof undefined;      // "undefined"
typeof null;           // "object" (bug, but standard)

2. Array Methods

const list = [1, 2, 3];

// Add/Remove (Mutate)
list.push(4);          // Add to end -> [1, 2, 3, 4]
list.pop();            // Remove from end -> [1, 2, 3]
list.shift();          // Remove from start -> [2, 3]
list.unshift(0);       // Add to start -> [0, 2, 3]

// Transform (Pure)
const doubled = list.map(x => x * 2);      // [0, 4, 6]
const filtered = list.filter(x => x > 1);  // [2, 3]
const sum = list.reduce((acc, val) => acc + val, 0); // 5

// Search
list.includes(2);      // true
list.find(x => x > 1);  // 2 (first match)

3. DOM Operations

// Query
const el = document.querySelector('.class-name');
const all = document.querySelectorAll('p'); // Returns NodeList

// Content & Attributes
el.textContent = "New Text"; // Safe text write
el.innerHTML = "<b>Bold</b>"; // HTML write
el.setAttribute('href', 'https://google.com');

// Class manipulation
el.classList.add('visible');
el.classList.remove('hidden');
el.classList.toggle('active');

// Creation & Attachment
const item = document.createElement('div');
document.body.appendChild(item);

4. Event Listeners

const btn = document.querySelector('button');

// Add event
function handler(e) {
  e.preventDefault(); // Prevents default form reloading
  e.stopPropagation(); // Prevents bubbling
  console.log("Clicked:", e.target);
}
btn.addEventListener('click', handler);

// Remove event
btn.removeEventListener('click', handler);

5. Async Fetch API

async function requestData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error("HTTP error");

    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error.message);
  }
}

6. Web Storage

// Store data
localStorage.setItem('theme', 'dark');

// Store object
localStorage.setItem('user', JSON.stringify({ name: 'Alice' }));

// Read data
const theme = localStorage.getItem('theme'); // "dark"
const user = JSON.parse(localStorage.getItem('user')); // { name: 'Alice' }
Published on Last updated: