JavaScript Cheatsheet
A complete JavaScript cheatsheet from beginner to advanced — variables, functions, objects, arrays, ES6+, async/await, DOM, classes, closures, prototypes, modern features, and best practices.
JavaScript is a high-level, multi-paradigm language primarily used for web development, but also widely used on the server (Node.js), mobile, and desktop. This cheatsheet covers beginner fundamentals through advanced modern features.
// Declarationvar oldWay = 1; // function-scoped, avoid in modern codelet changeable = 2; // block-scopedconst constant = 3; // block-scoped, cannot reassign
// Types (dynamic)typeof 42; // "number"typeof "hello"; // "string"typeof true; // "boolean"typeof undefined; // "undefined"typeof null; // "object" (historical bug)typeof {}; // "object"typeof []; // "object"typeof function(){}; // "function"typeof Symbol(); // "symbol"typeof 10n; // "bigint"
// Type conversionNumber("42"); // 42String(42); // "42"Boolean(0); // false!!"hello"; // true (double negation)+"42"; // 42 (unary plus)Falsy values: false, 0, "", null, undefined, NaN, 0n
// Arithmetic+ - * / % ** ++ --
// Comparison== != // loose (with coercion)=== !== // strict (preferred)> < >= <=
// Logical&& || ! ?? // nullish coalescing?. // optional chaining
// Assignment= += -= *= /= %= **=&&= ||= ??=
// Ternarycondition ? valueIfTrue : valueIfFalse// if / elseif (condition) { // ...} else if (other) { // ...} else { // ...}
// switchswitch (value) { case 1: // ... break; case 2: case 3: // fall-through break; default: // ...}
// loopsfor (let i = 0; i < 10; i++) { }for (const item of array) { } // valuesfor (const key in object) { } // keys (use carefully)while (condition) { }do { } while (condition);
// break / continue// labeled statements also supported// Function declaration (hoisted)function add(a, b) { return a + b;}
// Function expressionconst add = function(a, b) { return a + b;};
// Arrow functionconst add = (a, b) => a + b;const greet = name => `Hello, ${name}`;const multi = (a, b) => { const result = a * b; return result;};
// Default parametersfunction greet(name = "World") { return `Hello, ${name}`;}
// Rest parametersfunction sum(...numbers) { return numbers.reduce((a, b) => a + b, 0);}
// Arguments object (older style, avoid in modern code)function old() { console.log(arguments);}// Literalconst user = { name: "Rahim", age: 30, greet() { return `Hi, I'm ${this.name}`; }};
// Accessuser.name;user["name"];user.greet();
// Destructuringconst { name, age } = user;const { name: userName, age = 18 } = user;
// Spread / Restconst copy = { ...user };const { name, ...rest } = user;
// Computed propertyconst key = "email";const obj = { [key]: "rahim@example.com" };
// Object methodsObject.keys(obj);Object.values(obj);Object.entries(obj);Object.assign({}, obj1, obj2);Object.freeze(obj);Object.seal(obj);const arr = [1, 2, 3, 4, 5];
// Access & mutationarr[0];arr.length;arr.push(6); // add to endarr.pop(); // remove from endarr.unshift(0); // add to startarr.shift(); // remove from startarr.splice(2, 1, 99); // remove/replace
// Iteration & transformationarr.forEach(item => console.log(item));arr.map(x => x * 2);arr.filter(x => x > 2);arr.reduce((acc, x) => acc + x, 0);arr.find(x => x > 3);arr.findIndex(x => x > 3);arr.some(x => x > 4);arr.every(x => x > 0);arr.includes(3);arr.indexOf(3);arr.slice(1, 3); // non-mutatingarr.concat([6, 7]);arr.join("-");arr.flat();arr.flatMap(x => [x, x * 2]);
// Destructuringconst [first, second, ...rest] = arr;
// Spreadconst copy = [...arr];const combined = [...arr1, ...arr2];// Template literals`Hello, ${name}! You are ${age} years old.`;
// Destructuring (objects & arrays) — see above
// Spread / Rest — see above
// Modules// math.jsexport const PI = 3.14;export function add(a, b) { return a + b; }export default function multiply(a, b) { return a * b; }
// main.jsimport multiply, { PI, add } from "./math.js";import * as math from "./math.js";
// Optional chaininguser?.address?.city;arr?.[0];func?.();
// Nullish coalescingconst value = input ?? "default"; // only null/undefinedconst value2 = input || "default"; // any falsy
// Logical assignmenta &&= b;a ||= b;a ??= b;function fetchData(callback) { setTimeout(() => callback("data"), 1000);}const promise = new Promise((resolve, reject) => { // async work if (success) resolve(result); else reject(error);});
promise .then(result => console.log(result)) .catch(error => console.error(error)) .finally(() => console.log("done"));
// CreatingPromise.resolve(42);Promise.reject(new Error("fail"));Promise.all([p1, p2, p3]); // fails fastPromise.allSettled([p1, p2]); // waits for allPromise.race([p1, p2]); // first to settlePromise.any([p1, p2]); // first to fulfillasync function getUser(id) { try { const response = await fetch(`/api/users/${id}`); if (!response.ok) throw new Error("Network error"); const data = await response.json(); return data; } catch (err) { console.error(err); throw err; }}
// Parallelconst [user, posts] = await Promise.all([ getUser(1), getPosts(1)]);class Person { #privateField = 42; // private
constructor(name, age) { this.name = name; this.age = age; }
greet() { return `Hi, I'm ${this.name}`; }
static create(name) { return new Person(name, 0); }
get info() { return `${this.name} (${this.age})`; }
set age(value) { if (value < 0) throw new Error("Invalid age"); this._age = value; }}
class Employee extends Person { constructor(name, age, role) { super(name, age); this.role = role; }
greet() { return `${super.greet()} and I work as ${this.role}`; }}function makeCounter() { let count = 0; return function() { count += 1; return count; };}
const counter = makeCounter();counter(); // 1counter(); // 2
// Practical: data privacyfunction createBankAccount(initial) { let balance = initial; return { deposit(amount) { balance += amount; }, withdraw(amount) { balance -= amount; }, getBalance() { return balance; } };}// Depends on how the function is calledconst obj = { name: "Rahim", regular: function() { return this.name; }, // obj arrow: () => this.name, // lexical (outer this)};
// Explicit bindingfunc.call(obj, arg1, arg2);func.apply(obj, [arg1, arg2]);const bound = func.bind(obj);function Animal(name) { this.name = name;}Animal.prototype.speak = function() { return `${this.name} makes a sound`;};
function Dog(name) { Animal.call(this, name);}Dog.prototype = Object.create(Animal.prototype);Dog.prototype.constructor = Dog;Dog.prototype.speak = function() { return `${this.name} barks`;};Prefer modern class syntax for new code.
try { // risky code throw new Error("Something went wrong");} catch (err) { console.error(err.message); console.error(err.stack);} finally { // always runs}
// Custom errorclass ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; }}
// Promise rejectionfetch("/api") .catch(err => console.error(err));// Selectingdocument.getElementById("id");document.querySelector(".class");document.querySelectorAll("div");
// Creating & modifyingconst el = document.createElement("div");el.textContent = "Hello";el.innerHTML = "<strong>Hello</strong>";el.classList.add("active");el.classList.toggle("hidden");el.setAttribute("data-id", "123");el.style.color = "red";
// Insertingparent.appendChild(el);parent.append(el1, el2);parent.prepend(el);el.remove();
// Eventsel.addEventListener("click", (e) => { e.preventDefault(); e.stopPropagation(); console.log(e.target);});
// Event delegationparent.addEventListener("click", (e) => { if (e.target.matches(".button")) { // handle }});const id = Symbol("id");const obj = { [id]: 123 };function* idGenerator() { let id = 0; while (true) { yield id++; }}
const gen = idGenerator();gen.next().value; // 0gen.next().value; // 1const proxy = new Proxy(target, { get(obj, prop) { return prop in obj ? obj[prop] : "default"; }, set(obj, prop, value) { if (typeof value === "number") { obj[prop] = value; return true; } return false; }});const map = new Map();map.set("key", "value");map.get("key");map.has("key");map.delete("key");
const set = new Set([1, 2, 2, 3]); // {1, 2, 3}class Counter { #count = 0; #increment() { this.#count++; } up() { this.#increment(); }}// only inside ES modulesconst data = await fetch("/api").then(r => r.json());// Short-circuitconst name = user && user.name;const value = input || "default";
// Guard clausesfunction process(user) { if (!user) return; if (!user.isActive) return; // main logic}
// Debounce (basic)function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); };}
// Deep clone (modern)const clone = structuredClone(obj);
// Array uniquenessconst unique = [...new Set(array)];Best practices:
- Prefer
constandletovervar. - Prefer
===over==. - Use arrow functions for short callbacks; regular functions when you need
this. - Always handle promise rejections.
- Avoid mutating objects/arrays when possible (prefer spread / map / filter).
- Use modules instead of global scripts.
- Prefer
async/awaitover raw.then()chains for readability. - Keep functions small and focused.
- Use strict mode (
"use strict";) or ES modules (always strict).
// Fetchconst res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data)});const json = await res.json();
// Local StoragelocalStorage.setItem("key", "value");localStorage.getItem("key");localStorage.removeItem("key");
// JSONJSON.stringify(obj);JSON.parse(str);
// TimerssetTimeout(fn, 1000);setInterval(fn, 1000);clearTimeout(id);clearInterval(id);
// Consoleconsole.log / warn / error / table / time / timeEnd// Variablesconst x = 1; let y = 2;
// Functionconst add = (a, b) => a + b;
// Object / Arrayconst { name } = user;const [first, ...rest] = arr;const copy = { ...obj };
// Asyncasync function load() { const data = await fetch(url).then(r => r.json());}
// Classclass Person { constructor(name) { this.name = name; } greet() { return this.name; }}
// Errortry { ... } catch (e) { ... } finally { ... }- MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript
- JavaScript.info: https://javascript.info
- ECMAScript Spec: https://tc39.es/ecma262/
- Node.js Docs: https://nodejs.org/docs
- Can I use: https://caniuse.com
This cheatsheet targets modern JavaScript (ES2020+). Always check browser / Node version support for the newest features.
Frequently asked questions
What is the difference between var, let, and const?
var is function-scoped and hoisted. let and const are block-scoped. const cannot be reassigned (but object properties can still change).
What is a closure in JavaScript?
A closure is a function that remembers the variables from its outer lexical scope even after that outer function has finished executing.
How does async/await work?
async functions always return a Promise. await pauses execution until the Promise settles, making asynchronous code look synchronous.
What is the difference between == and ===?
== performs type coercion before comparison. === checks both value and type with no coercion. Prefer === in almost all cases.
What is the event loop?
The event loop is the mechanism that allows JavaScript to perform non-blocking I/O despite being single-threaded. It processes the call stack and the task/microtask queues.