Programming Languages
The language itself, properly — types, scope, this, async and the event loop.
Everything a working developer needs from the language: variables and types, coercion and equality, functions and closures, this, prototypes and classes, modules, async programming and the event loop, memory, and debugging in DevTools. Each subject links MDN or the specification.
The subjects follow the roadmap.sh JavaScript roadmap.
JavaScript is the language of the web and, through Node.js, of servers and tooling too. It is dynamically typed, prototype-based and single-threaded with an event loop. Start by knowing where it runs and how the language evolves.
A high-level, garbage-collected language with first-class functions, objects linked by prototypes, and a host (browser, Node) that provides I/O. The language itself is specified as ECMAScript.
Created in ten days at Netscape in 1995, standardised as ECMAScript in 1997, transformed by ES2015 (classes, modules, promises, let/const) and updated every year since.
Since ES2015 a new edition ships every June. Features move through TC39's stages 0–4; anything at stage 4 is in the next edition, and engines often ship it earlier.
In a <script> tag (use type="module" or defer), in the browser console, or with Node from the terminal. Online playgrounds are fine for quick experiments.
Variables name values. Modern code uses const by default and let when a binding must change; var survives in old code with surprising scoping. Understand declarations, hoisting and the three kinds of scope, and most "why is this undefined?" bugs disappear.
Three keywords, three behaviours: block-scoped let and const, function-scoped var. Declare before use, one binding per purpose.
Function-scoped, hoisted and initialised to undefined, redeclarable, and at the top level it becomes a property of globalThis. Avoid it in new code.
Block-scoped and reassignable. Each loop iteration gets a fresh binding, which fixes the classic closures-in-a-loop bug.
Block-scoped and cannot be reassigned — but the value is not frozen: a const object or array can still be mutated.
Declarations are processed before code runs. Function declarations are fully usable early; var reads as undefined; let, const and classes sit in the temporal dead zone and throw if touched before their line.
Names start with a letter, _ or $, are case-sensitive and cannot be reserved words. By convention: camelCase for values, PascalCase for classes, UPPER_SNAKE for true constants.
Scope decides where a name is visible. Inner scopes see outer ones, never the reverse, and lookups walk outward until the global scope.
Anything inside { } — an if, a loop, a bare block. let, const and class declarations live only inside it.
Each function call creates a scope for its parameters and locals — and for var, the smallest scope there is.
Visible everywhere. In modules, top-level declarations are module-scoped instead, which is one more reason to use modules.
JavaScript has seven primitive types — string, number, bigint, boolean, undefined, null, symbol — and objects for everything else, including arrays and functions. Primitives are immutable and compared by value; objects are compared by reference. Prototypes are how objects share behaviour.
Immutable UTF-16 text. Template literals interpolate and span lines; methods return new strings rather than changing the original.
IEEE-754 doubles: one type for integers and fractions. Hence 0.1 + 0.2 !== 0.3, NaN, Infinity, and safe integers only up to 2^53 − 1.
Arbitrary-precision integers, written 123n. They cannot be mixed with numbers in arithmetic without an explicit conversion.
true or false. Every value is also truthy or falsy in a condition — the falsy ones are false, 0, -0, 0n, "", null, undefined and NaN.
What you get for a declared-but-unassigned variable, a missing property or argument, and a function with no return.
An intentional "no value". typeof null is "object" — a historical bug. Use ?? and ?. to handle both null and undefined.
Unique, non-enumerable keys. Well-known symbols such as Symbol.iterator let your objects plug into language features.
Collections of keyed properties — the type of everything that is not a primitive, arrays and functions included. Learn literals, spread, destructuring and property descriptors.
Every object links to a prototype; a property missing on the object is looked up along that chain. Object.getPrototypeOf and Object.create work with it directly.
Objects inherit from other objects, not from classes — class and extends are syntax over this same prototype chain.
The standard library: Math, Date (and its successor Temporal), RegExp, Intl, JSON, Promise, the collections and the error types.
Returns a string naming a value's type. Remember its quirks: typeof null === "object" and functions report "function". Use Array.isArray for arrays.
Values change type all the time, sometimes because you asked and sometimes behind your back. Converting explicitly keeps intent clear; knowing the coercion rules explains the language's most famous surprises.
Conversion is explicit (Number(x)), coercion is implicit (x * 1). Both follow the same abstract operations — ToNumber, ToString, ToPrimitive.
String(), Number(), Boolean(), parseInt(s, 10), parseFloat. Prefer them to tricks like +x or !!x when readability matters.
+ with a string concatenates, other arithmetic converts to numbers, conditions convert to booleans, and == coerces before comparing.
Beyond plain objects, JavaScript ships indexed collections (arrays, typed arrays) and keyed collections (Map, Set and their weak variants). Choosing the right one makes code faster and clearer.
Values ordered by a numeric index: arrays for general use, typed arrays for raw binary data.
Ordered lists with map, filter, reduce, find and non-mutating toSorted, toReversed, with. Know which methods mutate in place.
Fixed-type views (Uint8Array, Float32Array…) over an ArrayBuffer — for binary files, WebGL, audio and WebAssembly.
Collections looked up by key, iterated in insertion order: Map and Set, plus WeakMap and WeakSet that do not keep their keys alive.
Key/value pairs where any value can be a key, with a real size and no prototype keys to trip over. Better than an object for dynamic lookup tables.
Object keys held weakly: when nothing else references a key, its entry can be garbage-collected. Ideal for attaching private data or caches to objects.
Unique values with fast membership checks. [...new Set(arr)] dedupes, and new methods like union and intersection do set algebra.
Objects held weakly — useful for marking objects as seen or processed without leaking them.
Data in a shape other programs agree on — JSON for exchange, and structuredClone for deep copies that keep Dates, Maps and cycles intact.
JSON.stringify and JSON.parse turn data into text and back. Dates become strings, functions and undefined vanish, and parse throws on invalid input.
JavaScript has four notions of "the same": loose (==), strict (===), SameValue (Object.is) and SameValueZero (used by includes, Map and Set). They disagree on NaN, -0 and type conversion — knowing which one an API uses avoids subtle bugs.
Converts the operands to a common type first, so "1" == 1 and null == undefined are true. The one idiomatic use is x == null to catch both.
Same type and same value, no conversion. Use it by default; its only oddities are NaN !== NaN and +0 === -0.
Like === but treats NaN as equal to itself and +0 as different from -0 — the SameValue algorithm exposed as a function.
The specification algorithm behind ==: the full table of which conversions happen for each pair of types.
The specification algorithm behind ===, deferring to Number::equal for numbers.
Like SameValue but +0 equals -0. Used by Array.prototype.includes, Map and Set keys.
The strictest notion of equality, used by Object.is and when redefining non-writable properties.
Repeat work with loops — or with array methods when you are transforming data. Pick for...of for values, for...in only for object keys, and know how break and continue (and labels) steer them.
The classic counter loop: initialiser, condition, update. Use let for the counter so each iteration gets its own binding.
Repeats while a condition holds — for loops whose end you cannot count in advance, like reading until a queue is empty.
Like while, but the body always runs at least once before the condition is checked.
Iterates enumerable string keys, inherited ones included. Fine for plain objects; never for arrays — use Object.keys/entries for clarity.
Iterates the values of any iterable — arrays, strings, Maps, Sets, generators — and works with await as for await...of.
break leaves the loop, continue skips to the next iteration; labels let you break out of an outer loop from an inner one.
Operators combine values into new ones. Beyond arithmetic, modern code leans on logical operators for defaults (??, ||=), optional chaining for safe access, and the conditional operator for small decisions. Precedence rules decide what groups with what — add parentheses when in doubt.
=, compound forms like +=, logical assignment (||=, &&=, ??=) and destructuring assignment.
<, >, <=, >= and the equality operators. Strings compare by code unit, so use localeCompare or Intl.Collator for human sorting.
+ - * / % ** and increment/decrement. % is a remainder, not a modulo, so it keeps the sign of the dividend.
Work on 32-bit integers: & | ^ ~ << >> >>>. Useful for flags, masks and low-level encoding.
&&, || and ! short-circuit and return one of their operands, not just booleans. ?? falls back only on null or undefined, unlike ||.
Most arithmetic works on BigInts too, but division truncates, unsigned right shift is not allowed, and BigInts cannot mix with numbers.
+ and += concatenate. Template literals are usually clearer than chains of +.
cond ? a : b — an expression, so it can sit inside JSX, template literals and returns. Nested ternaries quickly hurt readability.
Evaluates each operand and returns the last. Rare in hand-written code beyond for loop updates.
One operand: typeof, delete, void, unary +/-, ! and ~.
Decide what runs next with conditionals, and recover from failures with exceptions. Throw Error objects (never strings), catch only what you can handle, and use finally for cleanup that must always run.
Branches based on conditions: if...else for most cases, switch for many fixed values. Early returns keep nesting shallow.
Runs one block or another depending on a truthy condition; chain with else if.
Compares a value against cases with ===. Cases fall through unless you break or return; a lookup object is often cleaner.
Throwing interrupts normal flow and unwinds the stack until a catch handles it — or the program reports it as uncaught.
Throws any value, but throw Error instances so you get a stack trace; add context with new Error(msg, { cause }).
catch handles the error (the binding is optional), finally always runs — even after a return. With async code, it only catches what you await.
Error and its subclasses carry name, message, stack and cause; AggregateError bundles several. Extend Error for your own types.
Functions are values: pass them, return them, store them. Learn the different ways to define them, how parameters work, how scope and closures capture variables, and how the call stack runs them.
Parameters are local bindings filled from arguments in order; missing ones are undefined. Destructure an options object when there are more than two or three.
function f(x = 1) — the default applies when the argument is undefined (not null) and can refer to earlier parameters.
...args gathers the remaining arguments into a real array; it must be the last parameter.
Short syntax with lexical this and no arguments — ideal for callbacks, wrong for methods that need their own this.
Immediately invoked function expressions created a private scope before modules existed; an async IIFE still helps where top-level await is unavailable.
An array-like object of all arguments in non-arrow functions. Rest parameters replace it in modern code.
A function calling itself on a smaller problem until a base case — natural for trees. Deep recursion can overflow the stack, so convert to a loop when depth is unbounded.
Each call pushes a frame with its own locals onto the call stack and pops it on return; the stack trace you see in errors is that stack.
Scope is decided by where code is written, not where it is called from. Nested functions see the variables of the functions around them.
A function remembers the variables in scope where it was created, even after that scope has returned — the basis of private state, factories and memoisation.
Global functions such as parseInt, isNaN, encodeURIComponent and structuredClone, plus methods on the built-in objects.
In the browser, JavaScript works on the page through the Document Object Model: select elements, read and change them, listen for events and create new nodes. Learn querySelector, classList, addEventListener with event delegation, and why batching DOM writes matters for performance.
A safer dialect: assigning to undeclared variables throws, this is undefined in plain function calls, and silent failures become errors. Modules and classes are strict automatically; elsewhere add "use strict".
this is decided by how a function is called, not where it is written — the single biggest source of JavaScript confusion. Learn the call-site rules, how arrow functions opt out of them, and how to bind this explicitly.
Called as obj.method(), this is obj. Detach the method (const f = obj.method) and that link is lost.
A plain call f() gets undefined in strict mode and globalThis in sloppy mode.
At the top level of a script this is globalThis; at the top level of a module it is undefined.
In an addEventListener callback written as a regular function, this is the element the listener is attached to (same as event.currentTarget).
Arrow functions have no this of their own; they use the surrounding scope's, which is why they work so well as callbacks inside methods.
Using one object's method on another — like Array.prototype.slice.call(arguments) — by setting this explicitly.
call, apply and bind set this yourself instead of leaving it to the call site.
f.call(thisArg, a, b) invokes the function now with a chosen this and arguments listed individually.
f.apply(thisArg, [a, b]) is call with arguments as an array — mostly replaced by spread syntax.
f.bind(thisArg) returns a new function with this permanently fixed — and can pre-fill leading arguments.
JavaScript runs one task at a time, yet handles timers, network and user input without freezing. The event loop runs tasks and microtasks; callbacks, then promises, then async/await are the ways to say "continue when this finishes".
The loop takes one task, runs it to completion, then drains every microtask (promise reactions) before rendering and the next task. Long tasks block everything — clicks, painting, timers.
Schedules a task after at least the given delay — not exactly then, and never before the current code finishes. setTimeout(fn, 0) still waits for the queue.
Repeats a task every interval until cleared. For work that might overrun, chain setTimeouts instead so runs never overlap.
Passing a function to be called later — the original async pattern, still used for events and array methods.
Callbacks nested inside callbacks, with error handling repeated at every level. Promises flatten the pyramid into a chain.
An object for a future result: pending, then fulfilled or rejected. Chain with then, handle errors once with catch, and combine with all, allSettled, race and any.
Write promise code as if it were synchronous. await pauses only the async function, and errors are caught with ordinary try/catch.
Modules split code into files with explicit imports and exports and their own scope. ES modules are the standard everywhere; CommonJS is Node's older system you will still meet in packages and configs.
The iteration protocol is what makes for...of, spread and destructuring work on any object. Generators (function*) are the easy way to write iterators — lazy sequences that produce values on demand — and async generators do the same for streams of data.
Classes are templates for objects — constructor, methods, getters and setters, static members, extends with super, and truly private #fields. Under the hood they still create prototype chains.
Talk to servers over HTTP: send requests, read JSON, handle errors and timeouts, and cancel requests the user no longer needs.
Promise-based HTTP: await fetch(url), then await res.json(). It only rejects on network failure — check res.ok for 4xx/5xx — and takes an AbortSignal to cancel.
The original event-based HTTP API behind AJAX. You will read it in older code; it still offers upload progress events that fetch lacks.
JavaScript allocates and frees memory for you, but leaks still happen whenever something keeps a reference it no longer needs. Understand the lifecycle and how the garbage collector decides what is reachable.
Allocate when values are created, use them, release when they become unreachable — the last step is the collector's job.
Modern engines use mark-and-sweep from the roots (globals, the stack): anything unreachable is freed, cycles included. Weak references and FinalizationRegistry give limited control.
The browser's developer tools are where JavaScript problems get solved: breakpoints and stepping, network inspection, and profilers that show exactly where time and memory go.
Pause with breakpoints (conditional, DOM, XHR and event listener ones), step through code, inspect scope and the call stack, and log without editing code using logpoints.
Take heap snapshots before and after an action and compare them; look for detached DOM nodes and growing listener counts.
Record with the Performance panel to find long tasks, forced layouts and slow handlers; the flame chart shows which functions cost the most.