JavaScript Quick Reference Cheatsheet
Modern JavaScript Syntax, Methods, and Patterns
Category: Web Development
Level: Beginner — Intermediate
JavaScript quick reference cheatsheet covering variables, functions, arrays, objects, DOM manipulation, async/await, fetch API, destructuring, and modern ES6+ syntax.
📦 Variables & Data Types
// Variable declarations
var x = 1; // Function-scoped (avoid in modern JS)
let y = 2; // Block-scoped, reassignable
const z = 3; // Block-scoped, not reassignable
// Data types
const str = "Hello";
const num = 42;
const float = 3.14;
const bool = true;
const nothing = null;
const undef = undefined;
const sym = Symbol("id");
const big = 9007199254740991n; // BigInt
// Type checking
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof null // "object" (known quirk)
typeof undefined // "undefined"
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"
Array.isArray([]) // true
// Type conversion
Number("42") // 42
String(100) // "100"
Boolean(0) // false
Boolean("") // false
Boolean(null) // false
parseInt("42px") // 42
parseFloat("3.14") // 3.14
🔤 Strings
const s = "Hello, World!";
// Length
s.length // 13
// Access
s[0] // "H"
s.charAt(0) // "H"
// Search
s.indexOf("World") // 7 (-1 if not found)
s.includes("Hello") // true
s.startsWith("Hello") // true
s.endsWith("!") // true
// Modify (strings are immutable — always returns new string)
s.toUpperCase() // "HELLO, WORLD!"
s.toLowerCase() // "hello, world!"
s.trim() // Remove whitespace from both ends
s.trimStart() // Remove leading whitespace
s.trimEnd() // Remove trailing whitespace
s.replace("World", "JS") // Replace first match
s.replaceAll("l", "L") // Replace all
s.slice(0, 5) // "Hello"
s.split(", ") // ["Hello", "World!"]
// Template literals
const name = "Alice";
const age = 30;
`Hello, ${name}! You are ${age} years old.`
`${2 + 2} is four`
`Multi
line
string`
// Padding
"5".padStart(3, "0") // "005"
"hi".padEnd(6, "!") // "hi!!!!"
// Repeat
"ha".repeat(3) // "hahaha"
// Check content
s.match(/\d+/g) // Array of regex matches
s.search(/World/) // 7 (index of first match)
📋 Arrays
const arr = [1, 2, 3, 4, 5];
// Access
arr[0] // 1
arr.at(-1) // 5 (last element — ES2022)
// Add / Remove
arr.push(6) // Add to end → [1,2,3,4,5,6]
arr.pop() // Remove from end → returns 6
arr.unshift(0) // Add to start
arr.shift() // Remove from start
arr.splice(2, 1) // Remove 1 item at index 2
arr.splice(2, 0, 99) // Insert 99 at index 2
// Find
arr.indexOf(3) // 2 (-1 if not found)
arr.includes(3) // true
arr.find(x => x > 3) // 4 (first match)
arr.findIndex(x => x > 3) // 3 (index of first match)
// Transform (returns new array)
arr.map(x => x * 2) // [2,4,6,8,10]
arr.filter(x => x > 2) // [3,4,5]
arr.slice(1, 3) // [2,3] (doesn't modify original)
arr.flat() // Flatten one level
arr.flat(Infinity) // Flatten all levels
arr.flatMap(x => [x, x * 2]) // Map then flat
// Reduce
arr.reduce((acc, curr) => acc + curr, 0) // Sum = 15
arr.reduceRight((acc, curr) => acc + curr, 0)
// Test
arr.some(x => x > 4) // true (at least one)
arr.every(x => x > 0) // true (all)
// Sort (modifies original!)
arr.sort() // Lexicographic — be careful!
arr.sort((a, b) => a - b) // Numeric ascending
arr.sort((a, b) => b - a) // Numeric descending
arr.sort((a, b) => a.name.localeCompare(b.name)) // By string prop
// Join / Convert
arr.join(", ") // "1, 2, 3, 4, 5"
arr.join("") // "12345"
Array.from("hello") // ["h","e","l","l","o"]
Array.from({length: 3}, (_, i) => i) // [0,1,2]
[...arr] // Shallow copy (spread)
// Useful
arr.reverse() // Reverse in place
arr.fill(0, 2, 4) // Fill index 2-3 with 0
arr.concat([6, 7]) // Merge arrays
[...arr1, ...arr2] // Merge with spread
arr.length = 0 // Clear array (in place)
📖 Objects
const user = {
name: "Alice",
age: 30,
address: { city: "Phoenix" }
};
// Access
user.name // "Alice"
user["name"] // "Alice"
user.address.city // "Phoenix"
user?.missing?.prop // undefined (optional chaining)
// Modify
user.email = "alice@example.com"; // Add property
user.age = 31; // Update
delete user.address; // Remove
// Check
"name" in user // true
user.hasOwnProperty("name") // true
// Iterate
Object.keys(user) // ["name", "age"]
Object.values(user) // ["Alice", 30]
Object.entries(user) // [["name","Alice"],["age",30]]
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}
// Merge / Copy
const merged = { ...obj1, ...obj2 }; // Spread
const copy = Object.assign({}, user); // Shallow copy
const deepCopy = JSON.parse(JSON.stringify(user)); // Deep copy (simple)
// Destructuring
const { name, age } = user;
const { name: userName, age: userAge = 25 } = user; // Rename + default
const { address: { city } } = user; // Nested
// Shorthand
const name = "Alice";
const age = 30;
const person = { name, age }; // Same as { name: name, age: age }
// Computed property names
const key = "dynamic";
const obj = { [key]: "value" }; // { dynamic: "value" }
// Object methods
const obj = {
value: 42,
getValue() { return this.value; }
};
// Freezing
Object.freeze(obj); // Prevent modifications
Object.isFrozen(obj); // true
⚙️ Functions
// Function declaration (hoisted)
function add(a, b) {
return a + b;
}
// Function expression (not hoisted)
const add = function(a, b) {
return a + b;
};
// Arrow function
const add = (a, b) => a + b;
const square = x => x ** 2;
const noArgs = () => "hello";
const withBody = (a, b) => {
const sum = a + b;
return sum;
};
// Default parameters
function greet(name = "stranger") {
return `Hello, ${name}!`;
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
// Spread in calls
const nums = [1, 2, 3];
Math.max(...nums); // 3
// Destructuring parameters
function display({ name, age = 0 }) {
console.log(name, age);
}
// IIFE (Immediately Invoked)
(function() { console.log("runs immediately"); })();
(() => console.log("arrow IIFE"))();
// Higher-order functions
const double = x => x * 2;
const numbers = [1, 2, 3];
numbers.map(double);
// Closures
function counter() {
let count = 0;
return {
increment: () => ++count,
getCount: () => count
};
}
🔄 Async JavaScript
// Promises
const promise = new Promise((resolve, reject) => {
if (success) resolve(data);
else reject(new Error("Failed"));
});
promise
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log("always runs"));
// Promise combinators
Promise.all([p1, p2, p3]) // Resolves when ALL resolve
Promise.allSettled([p1, p2]) // Waits for all, success or failure
Promise.race([p1, p2]) // Resolves/rejects with first to finish
Promise.any([p1, p2]) // Resolves with first to succeed
// Async/Await
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Fetch failed:", error);
throw error;
}
}
// Parallel async operations
async function fetchAll() {
const [users, products] = await Promise.all([
fetch("/api/users").then(r => r.json()),
fetch("/api/products").then(r => r.json())
]);
return { users, products };
}
// Fetch API
// GET request
const response = await fetch("https://api.example.com/data");
const data = await response.json();
// POST with JSON body
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
},
body: JSON.stringify({ name: "Alice", age: 30 })
});
🌐 DOM Manipulation
// Select elements
document.getElementById("my-id")
document.querySelector(".my-class") // First match
document.querySelectorAll(".my-class") // All matches (NodeList)
document.querySelector("nav a.active") // CSS selector
// Create and add elements
const div = document.createElement("div");
div.textContent = "Hello";
div.className = "my-class";
div.id = "my-id";
parent.appendChild(div) // Add as last child
parent.prepend(div) // Add as first child
parent.insertBefore(div, sibling) // Insert before element
element.after(div) // Insert after element
element.remove() // Remove from DOM
// Modify elements
element.textContent = "New text" // Safe text (escapes HTML)
element.innerHTML = "Bold" // Parses HTML (be careful with user input)
element.setAttribute("href", "/")
element.getAttribute("href")
element.removeAttribute("disabled")
element.dataset.userId // data-user-id attribute
// Classes
element.classList.add("active")
element.classList.remove("active")
element.classList.toggle("active")
element.classList.contains("active") // true/false
// Styles
element.style.color = "red"
element.style.backgroundColor = "#fff"
element.style.display = "none"
getComputedStyle(element).color // Actual computed style
// Events
element.addEventListener("click", (event) => {
event.preventDefault() // Stop default behavior
event.stopPropagation() // Stop bubbling
console.log(event.target) // Element that triggered event
});
element.removeEventListener("click", handler);
// Common events
"click", "dblclick"
"mouseover", "mouseout", "mousemove"
"keydown", "keyup", "keypress"
"focus", "blur"
"submit", "change", "input"
"load", "DOMContentLoaded"
"scroll", "resize"
// Traversal
element.parentElement
element.children // HTMLCollection of child elements
element.firstElementChild
element.lastElementChild
element.nextElementSibling
element.previousElementSibling
element.closest(".parent-class") // Nearest matching ancestor
🆕 Modern ES6+ Syntax
// Destructuring
const [a, b, ...rest] = [1, 2, 3, 4, 5];
const { name, ...others } = user;
// Spread
const arr2 = [...arr1, 4, 5];
const obj2 = { ...obj1, key: "value" };
// Optional chaining
user?.address?.city // undefined if any part is null/undefined
user?.greet?.() // Call method if it exists
arr?.[0] // Array access with optional chaining
// Nullish coalescing
const value = user.name ?? "Anonymous"; // Use right side only if null/undefined
user.count ??= 0; // Assign only if null/undefined
// Logical assignment
x ||= "default" // Assign if x is falsy
x &&= "new value" // Assign if x is truthy
x ??= "default" // Assign if x is null/undefined
// Modules
export const name = "Alice";
export default function App() {}
export { name, age };
import { name } from "./module.js";
import App from "./App.js";
import * as module from "./module.js";
// Error handling
class AppError extends Error {
constructor(message, code) {
super(message);
this.name = "AppError";
this.code = code;
}
}
throw new AppError("Not found", 404);
// Generators
function* range(start, end) {
for (let i = start; i <= end; i++) yield i;
}
[...range(1, 5)] // [1, 2, 3, 4, 5]
// WeakMap / WeakSet (for private data patterns)
const privateData = new WeakMap();
privateData.set(obj, { secret: "value" });
→ Related: Web Development Essentials Guide | Build Your First Web App Tutorial | JavaScript Glossary Term
📬 New Cheatsheets Added Regularly
New quick-reference guides are added as the hub grows. Subscribe to the newsletter to know when new ones drop.
→ Subscribe to the Newsletter