Complete JavaScript in one page. One-shot notes covering every JavaScript topic from basics to advanced — variables, functions, OOP, async, DOM, ES6+ for 2026 interviews.
Everything you need to know about JavaScript, organized for maximum retention. Read this once and you'll have a solid mental model of the entire language.
Part 2: Variables & Types
Declaration Keywords
var x = 1; // function-scoped, hoisted as undefined, legacy
let y = 2; // block-scoped, TDZ, modern standard
const z = 3; // block-scoped, TDZ, immutable binding
All 8 Data Types
// 7 Primitives (stored by value)
number: 42, 3.14, NaN, Infinity, -Infinity
string: "hello", 'world', `template`
boolean: true, false
undefined: declared but not assigned
null: intentionally empty value
symbol: Symbol("unique")
bigint: 9007199254740993n
// 1 Object type (stored by reference)
object: {}, [], function(){}, /regex/, new Date()
Checking Types
typeof 42 // "number"
typeof null // "object" ← BUG
Array.isArray([]) // true
x instanceof Array // true
Part 3: Operators & Coercion
Equality
1 == "1" // true (type coercion — avoid)
1 === "1" // false (strict — always use this)
null == undefined // true (special case)
NaN === NaN // false (use Number.isNaN instead)
Logical Operators
// Short-circuit: returns value, not just true/false
"a" || "b" // "a" (first truthy)
"" || "b" // "b" (fallback)
"a" && "b" // "b" (last if all truthy)
null && fn() // null (fn not called)
// Nullish coalescing (only null/undefined triggers fallback)
null ?? "default" // "default"
0 ?? "default" // 0 (!! difference from ||)
"" ?? "default" // "" (!! difference from ||)
// Optional chaining
user?.address?.city // undefined if any link is null/undefined
arr?.[0] // safe array access
fn?.() // safe function call
Part 4: Functions — Everything
// 1. Function Declaration — hoisted
function add(a, b) { return a + b; }
// 2. Function Expression — not hoisted
const multiply = function(a, b) { return a * b; };
// 3. Arrow Function — concise, lexical 'this'
const square = n => n * n;
const greet = (name, greeting = "Hello") => `${greeting}, ${name}!`;
// 4. IIFE — Immediately Invoked
(function() { /* runs once */ })();
(() => { /* arrow IIFE */ })();
// 5. Generator — can pause/resume
function* gen() { yield 1; yield 2; yield 3; }
const g = gen();
g.next(); // { value: 1, done: false }
// 6. Async Function — returns Promise
async function fetchData() {
const data = await fetch("/api");
return data.json();
}
Function Parameters
// Default
function greet(name = "World") {}
// Rest (must be last)
function sum(first, ...rest) {}
// Destructured
function user({ name, age = 25 }) {}
// Arguments object (not in arrow functions)
function fn() { console.log(arguments); }
Part 5: Scope & Closures
Scope Types
1. Global Scope → accessible everywhere
2. Function Scope → var lives within function
3. Block Scope → let/const within {}
4. Module Scope → top-level stays in module
Closure (The King of JS Concepts)
// Closure = function + its lexical environment
function bank(initial) {
let balance = initial; // PRIVATE
return {
deposit(n) { balance += n; return balance; },
withdraw(n) { balance = Math.max(0, balance - n); return balance; },
check() { return balance; }
};
}
const account = bank(100);
account.deposit(50); // 150
account.withdraw(30); // 120
account.check(); // 120
// account.balance → undefined (private!)
Classic Loop Trap
// ❌ var — all share same i
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 3, 3, 3
}
// ✅ let — new binding per iteration
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0, 1, 2
}
Part 6: this & Prototypes
this Rules
1. Default: standalone fn → window (non-strict) / undefined (strict)
2. Method: obj.fn() → obj
3. new: new Fn() → new instance
4. Explicit: .call(ctx), .apply(ctx), .bind(ctx) → ctx
5. Arrow: inherits from lexical scope
Prototype Chain
instance
→ Constructor.prototype (shared methods)
→ Object.prototype (toString, hasOwnProperty...)
→ null
// Constructor pattern
function Animal(name) { this.name = name; } // own property
Animal.prototype.speak = function() { return this.name; }; // shared
// Modern ES6 class
class Animal {
constructor(name) { this.name = name; }
speak() { return this.name; }
}
class Dog extends Animal {
constructor(name) { super(name); }
bark() { return "Woof!"; }
}
Part 7: Arrays — Essential Methods
Mutating
push(x) — add to end
pop() — remove from end
unshift(x) — add to start
shift() — remove from start
splice(i,n,x) — remove/insert at index
sort(fn) — sort in-place
reverse() — reverse in-place
fill(x,s,e) — fill with value
Non-Mutating
slice(s,e) — extract portion
concat(arr) — join arrays
map(fn) — transform each
filter(fn) — keep matching
reduce(fn, init) — accumulate
find(fn) — first match
findIndex(fn) — index of first match
some(fn) — any match?
every(fn) — all match?
includes(x) — contains?
indexOf(x) — first index
flat(depth) — flatten
flatMap(fn) — map + flatten 1 level
Part 8: Objects — Essential Operations
// Create
const obj = { a: 1, b: 2 };
const obj2 = new Object({ a: 1 });
const obj3 = Object.create(proto);
// Read
obj.a // dot notation
obj["a"] // bracket notation
const { a } = obj; // destructuring
// Add/Update
obj.c = 3;
Object.assign(obj, { d: 4 });
const merged = { ...obj, e: 5 };
// Delete
delete obj.a;
// Iterate
Object.keys(obj) // ["b", "c", "d", "e"]
Object.values(obj) // [2, 3, 4, 5]
Object.entries(obj) // [["b",2], ...]
for (const key in obj) {} // includes prototype keys!
// Check
"b" in obj // true (includes prototype)
obj.hasOwnProperty("b") // true (own only)
// Clone
const shallow = { ...obj };
const deep = structuredClone(obj); // ES2022
// Freeze / Seal
Object.freeze(obj) // no changes at all (shallow)
Object.seal(obj) // no add/delete, can modify
Part 9: Promises & Async/Await
Promise Basics
// Create
const p = new Promise((resolve, reject) => {
// executor runs SYNCHRONOUSLY
setTimeout(() => resolve("data"), 1000);
});
// Consume
p.then(data => console.log(data))
.catch(err => console.error(err))
.finally(() => console.log("done"));
// Static methods
Promise.resolve("instant value")
Promise.reject(new Error("instant fail"))
Promise.all([p1, p2]) // all or fail fast
Promise.allSettled([p1, p2]) // wait for all
Promise.race([p1, p2]) // first to settle
Promise.any([p1, p2]) // first to fulfill
async/await
async function fn() {
// async always returns a Promise
const data = await fetchSomething(); // pauses fn
return data; // resolves the Promise
}
// Error handling
async function safe() {
try {
return await riskyOperation();
} catch (err) {
console.error(err.message);
return null;
}
}
// Parallel
const [a, b] = await Promise.all([fetch1(), fetch2()]);
// Sequential
const a = await step1();
const b = await step2(a);
Part 10: ES6+ Features
Destructuring
// Array
const [a, b, ...rest] = [1, 2, 3, 4, 5];
const [,, third] = arr; // skip with commas
// Object
const { name, age = 25, city: location } = user;
const { a: { b: deepVal } } = nested;
// Swap
[x, y] = [y, x];
// Function params
function fn({ name, role = "user" } = {}) {}
Spread & Rest
// Spread (expand)
const arr2 = [...arr1, ...arr3];
const obj2 = { ...obj1, override: "value" };
Math.max(...numbers);
// Rest (collect)
function fn(first, ...rest) {}
const { a, ...remaining } = obj;
Map, Set, WeakMap, WeakSet
// Map — any key type, preserves insertion order
const map = new Map();
map.set("key", "value");
map.set(obj, "object as key!");
map.get("key");
map.has("key");
map.size;
// Set — unique values
const set = new Set([1, 2, 2, 3, 3]);
// Set {1, 2, 3}
[...new Set(arr)] // deduplicate array
// WeakMap/WeakSet — keys are weakly held (GC-friendly)
// Use for: private data, caching, DOM associations
Part 11: Classes (ES6+)
class EventEmitter {
#listeners = {}; // private field (ES2022)
on(event, fn) {
(this.#listeners[event] ??= []).push(fn);
return this;
}
emit(event, ...args) {
this.#listeners[event]?.forEach(fn => fn(...args));
return this;
}
static create() {
return new EventEmitter();
}
}
class SpecialEmitter extends EventEmitter {
constructor() {
super();
this.type = "special";
}
}
const emitter = new SpecialEmitter();
emitter.on("click", data => console.log("Clicked:", data));
emitter.emit("click", { x: 100, y: 200 });
Clicked: { x: 100, y: 200 }
Part 12: Error Handling
// Basic
try {
const json = JSON.parse("bad json");
} catch (err) {
if (err instanceof SyntaxError) {
console.log("Parse error:", err.message);
} else {
throw err; // re-throw unexpected errors
}
} finally {
cleanup(); // always runs
}
// Custom errors
class AppError extends Error {
constructor(message, code, statusCode = 500) {
super(message);
this.name = "AppError";
this.code = code;
this.statusCode = statusCode;
}
}
// Async error handling
process.on("unhandledRejection", (reason) => {
console.error("Unhandled:", reason);
});
window.addEventListener("unhandledrejection", (e) => {
console.error(e.reason);
});
Part 13: DOM Essentials
// Query
document.querySelector("#id")
document.querySelectorAll(".class")
element.closest(".parent") // traverse up
// Modify
element.textContent = "text";
element.innerHTML = "<b>html</b>";
element.setAttribute("data-id", "1");
element.dataset.id // access data- attributes
element.classList.add/remove/toggle/contains/replace
// Events
element.addEventListener("click", handler, { once: true });
element.removeEventListener("click", handler);
// Event delegation (efficient)
document.body.addEventListener("click", (e) => {
if (e.target.matches(".btn")) handleButtonClick(e);
});
// Create & insert
const el = document.createElement("div");
parent.append(el); // after last child
parent.prepend(el); // before first child
sibling.before(el); // before sibling
sibling.after(el); // after sibling
el.remove(); // remove self
Part 14: Modules
// Named exports
export const PI = 3.14;
export function add(a, b) { return a + b; }
export class Calculator {}
// Default export (one per file)
export default class App {}
// Import
import { PI, add } from "./math.js";
import App from "./app.js";
import * as Math from "./math.js";
import { add as sum } from "./math.js";
// Dynamic import (lazy loading)
const module = await import("./heavy.js");
module.default();
One-Shot Memory Map 🗺️
JAVASCRIPT
├── Types: number, string, boolean, null, undefined, symbol, bigint, object
├── Scope: global → function → block → module
├── Hoisting: var(undefined), function(full), let/const(TDZ)
├── Closures: function + lexical env → private state
├── this: default/method/new/explicit/arrow
├── Prototype: [[Proto]] chain → inherited methods
├── Async:
│ ├── Callbacks → Promises → async/await
│ └── Event Loop: sync → microtasks → macrotasks
├── ES6+: class, arrow, destructure, spread, Map/Set, modules
└── Patterns: closure, module, factory, observer, memoize, curry