Skip to content

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.

// Declaration
var oldWay = 1; // function-scoped, avoid in modern code
let changeable = 2; // block-scoped
const 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 conversion
Number("42"); // 42
String(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
= += -= *= /= %= **=
&&= ||= ??=
// Ternary
condition ? valueIfTrue : valueIfFalse

// if / else
if (condition) {
// ...
} else if (other) {
// ...
} else {
// ...
}
// switch
switch (value) {
case 1:
// ...
break;
case 2:
case 3:
// fall-through
break;
default:
// ...
}
// loops
for (let i = 0; i < 10; i++) { }
for (const item of array) { } // values
for (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 expression
const add = function(a, b) {
return a + b;
};
// Arrow function
const add = (a, b) => a + b;
const greet = name => `Hello, ${name}`;
const multi = (a, b) => {
const result = a * b;
return result;
};
// Default parameters
function greet(name = "World") {
return `Hello, ${name}`;
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
// Arguments object (older style, avoid in modern code)
function old() {
console.log(arguments);
}

// Literal
const user = {
name: "Rahim",
age: 30,
greet() {
return `Hi, I'm ${this.name}`;
}
};
// Access
user.name;
user["name"];
user.greet();
// Destructuring
const { name, age } = user;
const { name: userName, age = 18 } = user;
// Spread / Rest
const copy = { ...user };
const { name, ...rest } = user;
// Computed property
const key = "email";
const obj = { [key]: "rahim@example.com" };
// Object methods
Object.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 & mutation
arr[0];
arr.length;
arr.push(6); // add to end
arr.pop(); // remove from end
arr.unshift(0); // add to start
arr.shift(); // remove from start
arr.splice(2, 1, 99); // remove/replace
// Iteration & transformation
arr.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-mutating
arr.concat([6, 7]);
arr.join("-");
arr.flat();
arr.flatMap(x => [x, x * 2]);
// Destructuring
const [first, second, ...rest] = arr;
// Spread
const 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.js
export const PI = 3.14;
export function add(a, b) { return a + b; }
export default function multiply(a, b) { return a * b; }
// main.js
import multiply, { PI, add } from "./math.js";
import * as math from "./math.js";
// Optional chaining
user?.address?.city;
arr?.[0];
func?.();
// Nullish coalescing
const value = input ?? "default"; // only null/undefined
const value2 = input || "default"; // any falsy
// Logical assignment
a &&= 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"));
// Creating
Promise.resolve(42);
Promise.reject(new Error("fail"));
Promise.all([p1, p2, p3]); // fails fast
Promise.allSettled([p1, p2]); // waits for all
Promise.race([p1, p2]); // first to settle
Promise.any([p1, p2]); // first to fulfill

async 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;
}
}
// Parallel
const [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(); // 1
counter(); // 2
// Practical: data privacy
function createBankAccount(initial) {
let balance = initial;
return {
deposit(amount) { balance += amount; },
withdraw(amount) { balance -= amount; },
getBalance() { return balance; }
};
}

// Depends on how the function is called
const obj = {
name: "Rahim",
regular: function() { return this.name; }, // obj
arrow: () => this.name, // lexical (outer this)
};
// Explicit binding
func.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 error
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
// Promise rejection
fetch("/api")
.catch(err => console.error(err));

// Selecting
document.getElementById("id");
document.querySelector(".class");
document.querySelectorAll("div");
// Creating & modifying
const 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";
// Inserting
parent.appendChild(el);
parent.append(el1, el2);
parent.prepend(el);
el.remove();
// Events
el.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
console.log(e.target);
});
// Event delegation
parent.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; // 0
gen.next().value; // 1

const 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 modules
const data = await fetch("/api").then(r => r.json());

// Short-circuit
const name = user && user.name;
const value = input || "default";
// Guard clauses
function 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 uniqueness
const unique = [...new Set(array)];

Best practices:

  • Prefer const and let over var.
  • 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/await over raw .then() chains for readability.
  • Keep functions small and focused.
  • Use strict mode ("use strict";) or ES modules (always strict).

// Fetch
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
const json = await res.json();
// Local Storage
localStorage.setItem("key", "value");
localStorage.getItem("key");
localStorage.removeItem("key");
// JSON
JSON.stringify(obj);
JSON.parse(str);
// Timers
setTimeout(fn, 1000);
setInterval(fn, 1000);
clearTimeout(id);
clearInterval(id);
// Console
console.log / warn / error / table / time / timeEnd

// Variables
const x = 1; let y = 2;
// Function
const add = (a, b) => a + b;
// Object / Array
const { name } = user;
const [first, ...rest] = arr;
const copy = { ...obj };
// Async
async function load() {
const data = await fetch(url).then(r => r.json());
}
// Class
class Person {
constructor(name) { this.name = name; }
greet() { return this.name; }
}
// Error
try { ... } catch (e) { ... } finally { ... }


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.

You're offline Check your connection.