Skip to content
Codeloom

Cheat Sheets

JavaScript Cheat Sheet

Modern JavaScript essentials — variables, functions, arrays, objects, promises, modules, and DOM manipulation in one quick-reference page.

8 sections 32 snippets

Variables and Types

Declarations
const name = 'Alice';   // immutable binding
let age = 30;           // mutable binding
// var is legacy — avoid it
Primitive types
typeof 'hello'    // 'string'
typeof 42         // 'number'
typeof true       // 'boolean'
typeof undefined  // 'undefined'
typeof null       // 'object' (quirk)
typeof Symbol()   // 'symbol'
typeof 9007199254740991n // 'bigint'
Template literals
`Hello, ${name}! You are ${age} years old.`
Nullish coalescing and optional chaining
const port = config.port ?? 3000;
const city = user?.address?.city;

Arrays

Create and access
const nums = [1, 2, 3, 4, 5];
nums[0];    // 1
nums.at(-1); // 5
Transform
nums.map(n => n * 2);       // [2, 4, 6, 8, 10]
nums.filter(n => n > 3);    // [4, 5]
nums.reduce((a, b) => a + b, 0); // 15
Search
nums.find(n => n > 3);      // 4
nums.findIndex(n => n > 3); // 3
nums.includes(3);           // true
Modify
nums.push(6);      // add to end
nums.pop();         // remove from end
nums.unshift(0);    // add to start
[...a, ...b];       // concat
Destructuring
const [first, second, ...rest] = nums;
const [[a, b], [c, d]] = [[1, 2], [3, 4]];

Objects

Create and access
const user = { name: 'Alice', age: 30 };
user.name;        // 'Alice'
user['age'];      // 30
Destructuring
const { name, age, email = '' } = user;
const { name: userName } = user; // rename
Spread and merge
const updated = { ...user, age: 31 };
const merged = { ...defaults, ...overrides };
Iterate
Object.keys(user);    // ['name', 'age']
Object.values(user);  // ['Alice', 30]
Object.entries(user); // [['name','Alice'], ['age',30]]

Functions

Arrow functions
const add = (a, b) => a + b;
const greet = name => `Hello, ${name}`;
const getUser = () => ({ name: 'Alice' });
Default parameters
function greet(name = 'World') {
  return `Hello, ${name}!`;
}
Rest parameters
function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
Closures
function counter() {
  let count = 0;
  return () => ++count;
}
const inc = counter();
inc(); // 1
inc(); // 2

Promises and Async

Create a promise
const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve('done'), 1000);
});
async / await
async function fetchUser(id) {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error(res.statusText);
  return res.json();
}
Promise combinators
Promise.all([p1, p2]);        // all must resolve
Promise.allSettled([p1, p2]); // wait for all
Promise.race([p1, p2]);       // first to settle
Promise.any([p1, p2]);        // first to resolve
Error handling
try {
  const data = await fetchUser(1);
} catch (err) {
  console.error(err.message);
}

Modules

Named exports
// math.js
export const PI = 3.14;
export function add(a, b) { return a + b; }

// app.js
import { PI, add } from './math.js';
Default export
// Logger.js
export default class Logger { ... }

// app.js
import Logger from './Logger.js';
Dynamic import
const { Chart } = await import('./chart.js');

DOM Manipulation

Select elements
document.querySelector('.btn');
document.querySelectorAll('li');
document.getElementById('app');
Modify elements
el.textContent = 'Hello';
el.innerHTML = '<strong>Bold</strong>';
el.classList.add('active');
el.setAttribute('data-id', '42');
el.style.color = 'red';
Events
btn.addEventListener('click', (e) => {
  e.preventDefault();
  console.log(e.target);
});
Create elements
const div = document.createElement('div');
div.textContent = 'New';
parent.appendChild(div);
parent.removeChild(child);

Common Patterns

Debounce
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}
Structured clone
const copy = structuredClone(original);
Map and Set
const map = new Map([['a', 1], ['b', 2]]);
map.get('a'); // 1

const set = new Set([1, 2, 2, 3]);
set.has(2); // true
set.size;   // 3
Error classes
class AppError extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
}