JavaScript — Quick Summary
Quick revision: every topic, key terms, and mnemonics for JavaScript.
This is a quick revision doc covering all 43 topics in the JavaScript collection. Open the linked notes if you want depth — this page is for cementing what we already know, fast.
Fundamentals
let, const, and var
What it is. Three ways to declare variables. var is function-scoped, let and const are block-scoped. const cannot be reassigned (but its object/array contents can mutate).
Key terms.
- Function scope —
varis accessible anywhere in the enclosing function. - Block scope —
let/constonly exist inside the{}they were declared in. - Temporal Dead Zone (TDZ) —
let/constare hoisted but uninitialized; touching them before the declaration throwsReferenceError.
Remember. Default to const. Reach for let only when reassigning. Avoid var in modern code.
Data Types & Type Coercion
What it is. JS has 7 primitives (string, number, boolean, null, undefined, symbol, bigint) and reference types (objects, arrays, functions). Primitives are compared by value; references by identity.
Key terms.
==vs===—==coerces,===doesn’t. Use===always (exception:x == nullcatches both null and undefined).- Falsy values — exactly 8:
false,0,-0,0n,"",null,undefined,NaN. Everything else is truthy (including[]and{}). typeof null === "object"— original JS bug, never fixed.+operator — string concatenation if either side is a string.-,*,/always coerce to number.
Remember. “Empty array, empty object — both truthy. typeof null lies.”
Hoisting
What it is. Before code runs, JS scans declarations and “moves” them to the top of their scope. var is initialized as undefined; let/const are hoisted but in TDZ; function declarations hoist fully (callable before their line).
Key terms.
- Declaration vs initialization — only declarations hoist; assignments stay where they are.
- TDZ — region from block start to the
let/constline where access throws. - Function expression — not hoisted (the variable is, the body isn’t).
Remember. “Functions hoist whole. var hoists empty. let/const hoist but bite.”
use strict
What it is. A directive ("use strict";) that turns silent JS gotchas into real errors — no implicit globals, no duplicate parameter names, no assignments to read-only properties.
Remember. Strict makes “bad syntax” loud. ES Modules and classes are already strict by default.
Destructuring
What it is. Unpacking values from objects/arrays into variables in one expression. {} for objects (match by name), [] for arrays (match by position).
Key terms.
- Renaming —
const { a: x } = objputsobj.ainx. - Defaults —
const { a = 1 } = obj. - Function param destructuring —
function fn({ a, b }) {}. - Swap —
[a, b] = [b, a].
Spread & Rest
What it is. Same ... syntax, opposite jobs. Spread expands an iterable into individual elements. Rest collects multiple elements into one array/object.
Key terms.
- Spread sites — function calls, array literals, object literals.
- Rest sites — function parameter list, destructuring patterns.
- Object merge — last property wins:
{ ...defaults, ...overrides }.
Remember. “Giving = spread. Getting = rest.”
Template Literals
What it is. Backtick strings that support ${expr} interpolation and multi-line text. Tagged templates let a function process the parts (e.g. styled-components, graphql-tag).
Remember. Backtick beats + every time.
Functions
Arrow Functions
What it is. ES6 shorter function syntax (a, b) => a + b. They have no own this, no arguments, can’t be used as constructors (new throws).
Key terms.
- Implicit return — single-expression body returns automatically; wrap object literal in
()to return one. - Lexical
this— inherits from enclosing scope, perfect for callbacks inside methods.
Remember. Arrows steal this from their parent. Don’t use them as object methods if you need this to be the object.
Higher-Order Functions
What it is. Functions that take a function as an argument or return a function. Foundation of functional JS.
Key terms.
map— transform each, return new array.filter— keep matching, return new array.reduce— collapse to one value with(acc, curr) => ..., takes an initial value.forEach— side effects only, returnsundefined.find— first match, orundefined.some/every— boolean: any pass / all pass.
Remember. Declarative > imperative. arr.filter(...).map(...) reads top-to-bottom.
Closures
What it is. A function bundled with references to its surrounding lexical scope. Every function in JS is technically a closure.
function counter() {
let count = 0;
return () => ++count;
}
Key terms.
- Data privacy — outer variables stay private; only the returned function can touch them.
- Loop trap —
varshares one binding across iterations;letcreates a fresh one each time.
Remember. Closures are how setTimeout/setInterval/event handlers remember their context.
Currying
What it is. Transforming f(a, b, c) into f(a)(b)(c) — a chain of unary functions. Useful for partial application: multiply(2) becomes double.
const multiply = a => b => a * b;
const double = multiply(2);
Memoization
What it is. Cache function results keyed by arguments. Same input → return cached output instead of recomputing. Pure functions only.
Remember. Stringify args (JSON.stringify) to make a cache key. Common in fib, API responses, expensive UI calculations.
Call, Apply and Bind
What it is. All three set what this is when a function runs. call invokes immediately with args one-by-one. apply invokes immediately with an args array. bind returns a new function with this permanently fixed (does NOT call).
Key terms.
- Method borrowing —
obj1.method.call(obj2, ...)to use one object’s method on another. Math.max.apply(null, arr)— classic pre-spread trick.bindfor callbacks —setTimeout(user.greet.bind(user), 1000).
Remember. “Call = comma. Apply = array. Bind = baked-in.”
IIFE
What it is. Immediately Invoked Function Expression: (function(){...})();. Runs once on definition, creates a private scope.
Remember. Pre-ES6 module pattern. Today: top-level await wrapper (async () => { ... })().
Scope & Execution
Lexical Scope
What it is. Inner functions can read variables from outer (parent) scopes, but not the other way around. Determined at write-time, not call-time.
Remember. “Where the function is written decides what it can see.”
Execution Context
What it is. Box that holds variables, functions, and this for each running piece of code. Two phases: Creation (memory allocated, hoisting happens) and Execution (line-by-line). Stored in the Call Stack.
Key terms.
- GEC — Global Execution Context, created once.
- FEC — Function Execution Context, one per function call.
- Scope Chain — links from current EC to outer ECs for variable lookup.
The this Keyword
What it is. this depends on how a function is called.
Key terms.
- Method call
obj.fn()—thisisobj. - Plain call
fn()—thisiswindow(orundefinedin strict). - Arrow — inherits
thisfrom enclosing scope. newClass —thisis the new instance.- DOM handler —
thisis the element (regular function only).
Remember. “Look at the left side of the dot when called — that’s this.”
Shallow Copy & Deep Copy
What it is. Shallow copy duplicates the top level only — nested objects still share references. Deep copy recursively copies everything.
Key terms.
- Shallow —
[...arr],{ ...obj },Object.assign({}, obj),arr.slice(). - Deep —
structuredClone(obj)(modern),JSON.parse(JSON.stringify(obj))(loses functions/dates/undefined).
Async JavaScript
Callbacks
What it is. A function passed as an argument to be “called back” later. Sync (map, forEach) or async (setTimeout, fs.readFile).
Key terms.
- Callback Hell / Pyramid of Doom — deeply nested callbacks for sequential async steps.
- Error-first callback — Node convention
(err, data) => {}.
Promises
What it is. An object representing the future result of an async operation. States: pending, fulfilled, rejected. Once settled, never changes.
Key terms.
.then(onFulfilled)— handle success, returns a new Promise..catch(onRejected)— handle rejection (one at the end of a chain catches all)..finally()— runs no matter what.- Chaining — return a Promise from
.thenand the next.thenwaits.
Remember. Promises flatten callback hell. .catch at the end catches errors from any upstream .then.
Async/Await
What it is. Syntactic sugar over Promises. async functions always return a Promise. await pauses inside the async function until the awaited Promise settles.
Key terms.
try/catch— normal sync-style error handling for awaited code.- Sequential —
awaitone after another (slow). - Parallel —
await Promise.all([fn1(), fn2()])(fast when independent). forEachtrap —forEachdoes NOT wait for async callbacks. Usefor...offor sequential,Promise.all(arr.map(...))for parallel.
Promise Methods
What it is. Four static helpers for handling multiple Promises.
| Method | Resolves when | Rejects when |
|---|---|---|
Promise.all | ALL resolve | ANY rejects (fail-fast) |
Promise.allSettled | ALL settle | Never |
Promise.race | First to settle (resolve OR reject) | First to settle (if reject) |
Promise.any | First to resolve | ALL reject (AggregateError) |
Remember. “all = all-or-nothing, allSettled = no-fail-status-report, race = first-finisher, any = first-success.”
Error Handling
What it is. try/catch/finally for synchronous failures; .catch or try/catch with await for async. Throw Error instances (not strings) for stack traces.
Key terms.
- Built-in errors —
TypeError,ReferenceError,SyntaxError,RangeError. - Custom error class —
class ValidationError extends Error. instanceof— check error type before handling.- Global —
window.addEventListener("unhandledrejection", ...).
Event Loop
What it is. JS is single-threaded. The event loop coordinates the Call Stack, Web APIs, Microtask Queue (Promises, queueMicrotask, MutationObserver, async/await continuations), and Callback Queue (setTimeout, setInterval, I/O).
Key terms.
- Microtask priority — drained completely between macrotasks.
setTimeout(fn, 0)— runs after sync + all microtasks; not “immediate”.
Remember. “Sync first → drain microtasks → one macrotask → drain microtasks → repeat.”
console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => console.log(3));
console.log(4);
// 1, 4, 3, 2
Debouncing and Throttling
What it is. Two ways to rate-limit a function for rapid events.
Key terms.
- Debounce — fires once after the user stops for N ms (search-as-you-type, resize-end).
- Throttle — fires at most once every N ms while events keep coming (scroll, mousemove).
Remember. “Debounce waits for silence. Throttle ticks on a clock.”
Objects & Prototypes
Objects
What it is. Key-value bags. Created via literals {}, constructor functions (new Foo()), or Object.create(proto).
Key terms.
Object.keys/values/entries— iterate.Object.freeze— fully locked.Object.seal— no add/remove but existing keys mutable. Both shallow.Object.assign(target, ...sources)/ spread — merge, last wins.- Computed key —
{ [field]: value }. - Shorthand —
{ name, age }when var names match keys.
Prototypal Inheritance
What it is. Every object has a hidden link [[Prototype]] to another object. Property lookup walks the chain until found or until null.
Key terms.
Object.getPrototypeOf/__proto__— read the link.fn.prototype— the object thatnew fn()instances will inherit from.hasOwnProperty(key)— own property only, ignores chain.key in obj— checks chain too.
Remember. Classes are sugar over this. Methods on prototype are shared once across all instances.
Classes
What it is. ES6 syntactic sugar over constructor functions and prototypes. Provides constructor, methods, extends/super, static, private #field, getters/setters.
Key terms.
super()— must call beforethisin a child constructor.static— belongs to class, not instances.#private— true privacy; not even subclasses can read.get/set— computed props that look like fields.
Remember. typeof Class === "function" — classes are functions.
Iterators: for…in vs for…of
What it is. for...in iterates keys (including inherited enumerable ones). for...of iterates values of any iterable (arrays, strings, Maps, Sets).
Remember. “in for keys, of for values.” Don’t use for...in on arrays.
Map & Set
What it is.
- Map — keys can be any type (incl. objects), preserves insertion order, has
.size. Better than objects for frequent add/delete or non-string keys. - Set — collection of unique values.
[...new Set(arr)]deduplicates. - WeakMap / WeakSet — keys/values must be objects, weakly held (GC can reclaim), not iterable. Used for metadata that shouldn’t keep objects alive.
DOM & Events
Events
What it is. Notifications fired when something happens in the page (click, load, keypress, scroll, etc.). JS handlers respond.
Event Bindings
What it is. addEventListener (multiple handlers, third-arg options like once, capture, passive) vs onclick property (single handler, gets overwritten). removeEventListener needs the same function reference.
Event Propagation, Bubbling and Capturing
What it is. Three phases when an event fires:
- Capturing — top → target.
- Target — fires on the actual element.
- Bubbling — target → top (default for handlers).
addEventListener(type, fn, true) runs in the capture phase. event.stopPropagation() halts the chain.
Event Delegation
What it is. One listener on a parent uses event.target to handle events from any descendant. Replaces N listeners with 1.
Key terms.
event.target— what was actually clicked.event.currentTarget— element with the listener attached.
Remember. “Listen up high, ask event.target who fired it.” Auto-supports dynamically added children.
DOM Manipulation
What it is. Selecting (getElementById, querySelector, querySelectorAll), creating (createElement, createTextNode), modifying (textContent, innerHTML, setAttribute, classList.add/remove/toggle), inserting (appendChild, append, prepend, insertBefore), and removing (element.remove()).
Remember. Prefer textContent over innerHTML for plain text — faster and XSS-safe.
Web Storage & Cookies
What it is.
- localStorage — ~5 MB, persists forever, not sent to server.
- sessionStorage — ~5 MB, cleared on tab close, not sent to server.
- Cookies — ~4 KB, sent on every HTTP request, configurable expiry.
Remember. Server needs it on every request → cookie. Otherwise → localStorage (persistent) or sessionStorage (tab-only).
ES6+ & Modern JS
Modules
What it is. Per-file scoping with explicit export/import. Named exports keep the same identifier; default exports can be renamed. Dynamic import('./mod.js') returns a Promise — used for code splitting.
Key terms.
- CommonJS —
require/module.exports, synchronous, runtime. - ES Modules —
import/export, statically analyzed, top-level (exceptimport()).
Optional Chaining & Nullish Coalescing
What it is.
?.— short-circuits toundefinedif any link isnull/undefined. Works on properties (a?.b), method calls (fn?.()), array access (arr?.[0]).??— fallback only fornull/undefined. Unlike||, it preserves0,"",false.
Remember. “?? keeps falsy-but-real values. || nukes them all.”
Symbols
What it is. Primitive that’s always unique. Used as object keys that won’t clash with anything else; not enumerable in for...in/Object.keys/JSON.stringify.
Key terms.
Symbol.for(key)— global registry, returns same symbol for same key.Symbol.iterator— makes an object iterable (for...of, spread).Symbol.toPrimitive— controls type coercion to primitive.
Proxy & Reflect
What it is. Proxy wraps an object with handler traps (get, set, has, deleteProperty, apply, …) that intercept operations. Reflect provides static methods matching every trap so we can forward to the default behavior cleanly.
Remember. Vue 3’s reactivity is built on Proxy. Useful for validation, logging, observable state.
Patterns & Practice
Output-Based Questions
What it is. Classic “what prints?” interview ammo. Common categories:
var+setTimeoutin loops →3,3,3(useletfor0,1,2).==coercion:[] == false,[] == ![],'' == 0— all true.thisin arrow vs regular function in object literal.- Microtask vs macrotask order.
typeof nullis"object",typeof NaNis"number",typeof typeof 1is"string".[1,2,3].map(parseInt)→[1, NaN, NaN]becauseparseIntgets(value, index).- Object equality:
{x:1} === {x:1}isfalse(reference compare).
Remember. When stuck: identify if it’s hoisting, coercion, this, or event loop — those four cover almost every trick.
Polyfills
What it is. Re-implementing built-ins to prove deep understanding.
Array.prototype.myMap = function(cb, thisArg) {
const out = [];
for (let i = 0; i < this.length; i++)
if (i in this) out.push(cb.call(thisArg, this[i], i, this));
return out;
};
Function.prototype.myBind = function(thisArg, ...bound) {
const fn = this;
return function(...rest) { return fn.apply(thisArg, [...bound, ...rest]); };
};
Remember. Callback signature is (element, index, array). reduce without initial value uses arr[0] and starts from index 1.
Design Patterns
What it is. Four patterns that come up constantly.
| Pattern | Idea | Real-world |
|---|---|---|
| Module | Closure-based private state + public API | jQuery, pre-ESM libraries |
| Singleton | Single shared instance | Redux store, DB connections |
| Observer (pub/sub) | Subscribe + notify | EventEmitter, addEventListener, RxJS, Vue reactivity |
| Factory | Function returns objects without new | React.createElement, express() |
Remember. All four are easy to write in vanilla JS — no library needed.