Quick Reference JavaScript Cheatsheet
Complete modern JavaScript quick reference — variables, operators, strings, arrays, objects,
functions, classes, async/await, DOM, modules, built-ins, ESNext syntax, and colorized snippets.
let count = 0;
const PI = 3.14;
var legacy = "old";
typeof 42;
typeof null;
Number.isNaN(x);
Array.isArray(arr);
a + b; a - b; a * b; a / b; a % b;
a ** b;
a ++; a --;
a === b; a !== b;
a == b;
a && b; a || b; !a;
a ?? b;
obj?.prop?.method?.();
cond ? yes : no;
x += 1; s += "!"; const name = "Ada";
const msg = `Hello, ${name}!`;
msg.length; msg.toUpperCase(); msg.includes("Ada");
"a,b,c".split(",");
" hi ".trim();
"hello".slice(1, 4);
"hi".repeat(3); "x".padStart(3, "0");
String(42); 42.toString(16); const nums = [1, 2, 3];
nums.push(4); nums.pop();
nums.unshift(0); nums.shift();
nums.map(n => n * 2);
nums.filter(n => n % 2 === 0);
nums.reduce((a, n) => a + n, 0);
nums.find(n => n > 1); nums.includes(2);
nums.slice(0, 2); nums.splice(1, 1, 9);
[...nums, 5];
const [first, ...rest] = nums; const user = {
id: 1,
name: "Sam",
greet() { return `Hi ${this.name}`; },
};
user.name; user['name'];
const { name, id: uid } = user;
const copy = { ...user, role: "admin" };
Object.keys(user); Object.values(user);
Object.entries(user);
Object.assign({}, user); function add(a, b = 0) {
return a + b;
}
const mul = function(a, b) { return a * b; };
const div = (a, b) => a / b;
const sq = n => n ** 2;
function sum(...nums) {
return nums.reduce((a, n) => a + n, 0);
}
(function() { })(); if (x > 0) {
} else if (x < 0) {
} else {
}
switch (status) {
case "ok": handleOk(); break;
case "err": handleErr(); break;
default: handleOther();
}
for (let i = 0; i < n; i++) { }
for (const item of list) { }
for (const key in obj) { }
list.forEach(item => { });
while (cond) { }
do { } while (cond);
try { } catch (e) { } finally { } class Person {
constructor(name) {
this.name = name;
}
hello() {
return `Hi, ${this.name}`;
}
static create(name) {
return new Person(name);
}
}
class Admin extends Person {
hello() {
return super.hello() + " (admin)";
}
}
const p = new Admin("Sam");
p instanceof Person; const p = new Promise((resolve, reject) => {
setTimeout(() => resolve("done"), 200);
});
p
.then(v => console.log(v))
.catch(e => console.error(e))
.finally(() => {});
async function load() {
try {
const res = await fetch("/api");
const data = await res.json();
return data;
} catch (e) {
console.error(e);
}
}
Promise.all([p1, p2]);
Promise.race([p1, p2]);
Promise.allSettled([p1, p2]); const el = document.querySelector(".btn");
document.querySelectorAll("li");
document.getElementById("app");
el.textContent = "Click";
el.classList.add("active");
el.setAttribute("aria-pressed", "true");
el.style.display = "block";
el.addEventListener("click", (e) => {
e.preventDefault();
console.log(e.target);
});
const node = document.createElement("div");
parent.append(node); node.remove();
export const PI = 3.14;
export function add(a, b) { return a + b; }
export default function main() { }
import main, { add, PI } from "./math.js";
import * as math from "./math.js";
const mod = await import("./lazy.js"); JSON.stringify(obj); JSON.parse(str);
Math.floor(3.7); Math.random(); Math.max(...arr);
const d = new Date(); d.toISOString();
const map = new Map([["a", 1]]);
map.set("b", 2); map.get("a");
const set = new Set([1, 2, 2]); set.has(1);
setTimeout(fn, 1000); clearTimeout(id);
localStorage.setItem("k", "v"); localStorage.getItem("k");
const { a, b: bee, ...rest } = obj;
const [x, y = 0, ...more] = arr;
const port = env.PORT ?? 3000;
const len = arr?.length ?? 0;
x ||= "default"; y &&= f(); z ??= 1;
class Counter { #n = 0; inc() { this.#n++; } }
arr.at(-1); Object.hasOwn(obj, "key"); ⚠️Gotchas & Interview Tips - Prefer
=== over ==; know that typeof null === "object". const prevents rebinding, not mutation — freeze or copy if needed. - Arrow functions do not bind their own
this — do not use as methods that need instance this. - Array
sort() mutates and sorts as strings by default — pass a compare fn for numbers. - Closures capture variables by reference — be careful in loops with
var (use let). - Promises: always handle rejections;
async functions always return a Promise. innerHTML with user input is an XSS risk — prefer textContent or sanitization. - Event listeners: remove when components unmount; use event delegation for lists.
Next: JavaScript tutorial ·
Cheatsheet hub ·
HTML ·
CSS |