JavaScript Cheat Sheet

Essential JavaScript syntax and methods in one page. Variables, arrays, objects, string methods, DOM manipulation, async/await, and modern ES6+ features.

Variables & Types Strings Arrays Objects Functions Async / Await DOM Manipulation Modern ES6+ Features

Variables & Types

const x = 1 Block-scoped constant (cannot reassign)
let y = 2 Block-scoped variable (can reassign)
var z = 3 Function-scoped variable (avoid in modern JS)
typeof x Returns type as string: "number", "string", "object", etc.
Array.isArray(arr) Check if value is an array (typeof returns "object")
x === y Strict equality (checks value and type)
x == y Loose equality (coerces types — avoid)

Strings

`Hello ${name}` Template literal with interpolation
str.length String length
str.includes("abc") Check if string contains substring
str.startsWith("ab") Check if string starts with prefix
str.slice(0, 5) Extract substring (start, end)
str.split(",") Split into array by delimiter
str.trim() Remove leading/trailing whitespace
str.replace(/old/g, "new") Replace all occurrences (regex)
str.padStart(5, "0") Pad start to length with character
str.toUpperCase() Convert to uppercase

Arrays

arr.push(item) Add to end, returns new length
arr.pop() Remove from end, returns removed item
arr.unshift(item) Add to beginning
arr.shift() Remove from beginning
arr.map(x => x * 2) Transform each element, returns new array
arr.filter(x => x > 0) Keep elements that pass test
arr.reduce((sum, x) => sum + x, 0) Reduce to single value
arr.find(x => x.id === 1) Find first matching element
arr.findIndex(x => x.id === 1) Find index of first match (-1 if none)
arr.includes(item) Check if array contains item
arr.sort((a, b) => a - b) Sort in place (numeric ascending)
arr.flat(Infinity) Flatten nested arrays
[...arr1, ...arr2] Merge arrays (spread operator)

Objects

{ ...obj, key: val } Spread + override (shallow copy)
Object.keys(obj) Array of keys
Object.values(obj) Array of values
Object.entries(obj) Array of [key, value] pairs
Object.assign({}, obj) Shallow clone
structuredClone(obj) Deep clone (modern)
const { a, b } = obj Destructuring assignment
obj?.nested?.prop Optional chaining (returns undefined if null)
obj.key ?? "default" Nullish coalescing (default for null/undefined)

Functions

const fn = (a, b) => a + b Arrow function (concise)
const fn = (a, b = 10) => {} Default parameter
const fn = (...args) => {} Rest parameters (array)
fn(...arr) Spread arguments
const fn = (a) => ({ key: a }) Return object literal from arrow
setTimeout(fn, 1000) Run function after delay (ms)
setInterval(fn, 1000) Run function repeatedly every N ms

Async / Await

async function fn() {} Declare async function
const data = await fetch(url) Wait for Promise to resolve
const json = await res.json() Parse response as JSON
try { await fn() } catch(e) {} Handle async errors
await Promise.all([p1, p2]) Wait for all Promises (parallel)
await Promise.race([p1, p2]) Wait for first Promise to settle
await Promise.allSettled([p1, p2]) Wait for all, get results + errors

DOM Manipulation

document.querySelector(".class") Select first matching element
document.querySelectorAll("div") Select all matching elements
el.textContent = "text" Set text content (safe, no HTML)
el.innerHTML = "<b>html</b>" Set HTML content (XSS risk)
el.classList.add("active") Add CSS class
el.classList.toggle("active") Toggle CSS class on/off
el.addEventListener("click", fn) Add event listener
el.setAttribute("data-id", "1") Set HTML attribute
el.style.display = "none" Set inline CSS style

Modern ES6+ Features

const [a, ...rest] = arr Array destructuring with rest
for (const item of arr) {} Iterate array values
for (const [k, v] of Object.entries(obj)) {} Iterate object entries
new Map() / new Set() Map (key-value) / Set (unique values)
import { fn } from "./mod.js" ES module import
export const fn = () => {} ES module named export
arr.at(-1) Get last element (negative index)
Object.hasOwn(obj, "key") Check own property (replaces hasOwnProperty)

Try It Live

Test these patterns with our free JSON Formatter. No signup needed.

Open JSON Formatter →
Step-by-Step Guide

How to Format JSON Online

Read Guide →

More Cheat Sheets