JavaScript Roadmap
JavaScript is the language of the web browser and one of the most used languages for servers, tools and apps. Every front-end and full-stack role requires it, and many back-end, mobile and testing roles do too. Frameworks such as React, Vue and Angular, and runtimes such as Node.js, all sit on top of it, so gaps in the core language show up everywhere.
The language is easy to start and surprisingly deep. Interviews go beyond syntax: they ask you to predict output involving hoisting, coercion and the event loop, to explain closures and this, to write promise-based code correctly, and to debug memory leaks or slow pages.
This roadmap starts with running your first script and moves through variables and types, operators, control flow, functions, objects and prototypes, collections, asynchronous code, the DOM and modules, and finishes with memory, debugging and performance. Each topic explains the idea plainly, shows a short example and gives you an exercise. Work through it in order and you will be ready for JavaScript interviews and for learning any framework on top.
- Level
- Beginner to advanced
- Time
- 12–16 weeks at about 8 hours a week
- Scope
- 59 topics in 10 stages
- Before you start
- Basic HTML Roadmap: elements, attributes and forms; Basic CSS Roadmap: selectors and classes; Comfort with a code editor and a terminal
What you will be able to do
- Explain JavaScript types, coercion and equality and predict the output of tricky snippets.
- Write clean functions and explain scope, hoisting, closures and
this. - Model data with objects, classes and the right built-in collections.
- Write correct asynchronous code with promises and async/await and explain the event loop.
- Build interactive pages with DOM APIs, events and ES modules.
- Debug errors, memory leaks and slow code with browser DevTools.
The roadmap at a glance
- Stage 1Introduction to JavaScriptBeginner · 2–4 days · 3 topics
- Stage 2Variables and Data TypesBeginner · 1–2 weeks · 8 topics
- Stage 3Expressions & Operators and Type ConversionBeginner · 1 week · 6 topics
- Stage 4Control Flow and Error HandlingBeginner · 1 week · 5 topics
- Stage 5FunctionsBeginner · 1–2 weeks · 7 topics
- Stage 6Objects, this, Prototypes and ClassesIntermediate · 2 weeks · 7 topics
- Stage 7Data Structures and IterationIntermediate · 1–2 weeks · 6 topics
- Stage 8Asynchronous JavaScriptIntermediate · 2 weeks · 6 topics
- Stage 9The Browser: DOM, Events and ModulesIntermediate · 1–2 weeks · 5 topics
- Stage 10Memory, Debugging and PerformanceAdvanced · 1–2 weeks · 6 topics
Stage 1 Introduction to JavaScript
Goal. Run JavaScript in the browser and in Node.js and know where the language came from.
What is JavaScript Core
JavaScript is the programming language built into every web browser. HTML gives a page structure, CSS styles it, and JavaScript makes it respond: validating a form, loading new data without a reload, drawing charts, running whole applications such as email clients and editors.
It also runs outside the browser. Node.js, Deno and Bun execute it on servers and in command-line tools, and frameworks use it for mobile and desktop apps. That reach is why so many roles ask for it.
Key traits you will meet throughout this roadmap: it is dynamically typed (variables can hold any type), it treats functions as values, it uses prototypes for inheritance, and it runs your code on a single thread with an event loop for asynchronous work. Despite the name, it has nothing to do with Java.
Practice. List five things on a website you use daily that need JavaScript to work.
History of JavaScript and JavaScript Versions Recommended
JavaScript was created at Netscape in 1995 in a matter of days, which explains some of its odd corners that can never be removed without breaking old sites. It was standardised as ECMAScript, and the committee that maintains it is called TC39.
Versions you should recognise:
- ES5 (2009) added strict mode, JSON and array methods like
mapandfilter. - ES2015, often called ES6, was the big modernisation:
let,const, arrow functions, classes, modules, promises, template literals, destructuring,MapandSet. - Since then a new edition comes out each year with smaller additions, such as
async/await, optional chaining andArray.prototype.at.
New features go through numbered stages before being accepted. When you read "ES6+" in a job advert, it simply means modern JavaScript.
Practice. Pick three features introduced since 2015 and write a short example of each.
How to run JavaScript Core
There are several places to run code while you learn.
- Browser console: open DevTools and type expressions directly. Ideal for quick experiments.
- A script in a page: link a file from HTML.
<script src="app.js" defer></script>- Node.js: install it, then run
node app.jsin a terminal. Good for practising language features without HTML. - Online sandboxes and editor extensions also work.
Use console.log to print values, and also try console.table for arrays of objects and console.error for problems. Set up a code editor with a formatter such as Prettier and a linter such as ESLint early; the linter catches many beginner mistakes before you run the code.
Practice. Run the same console.log program in the browser console, from an HTML page and with Node.js.
Stage 2 Variables and Data Types
Goal. Declare variables correctly and explain every JavaScript data type and how it behaves.
All about Variables: Variable Declarations with let, const and var Core
A variable is a named reference to a value. Modern code uses two variable declarations, plus one legacy form.
- The const keyword declares a binding that cannot be reassigned. Use it by default.
letdeclares a binding you will reassign, such as a counter.- The var keyword is the pre-2015 form. It is function-scoped, can be redeclared and is hoisted with the value
undefined, which causes bugs. Avoid it in new code, but recognise it in old code.
const user = { name: 'Asha' };
user.name = 'Ben'; // allowed: the object changes, the binding does not
let count = 0;
count += 1;const does not make a value immutable; it only stops reassignment. Use Object.freeze for a shallow read-only object.
Practice. Rewrite a snippet that uses var everywhere with const and let, and explain each choice.
Naming Rules Core
Identifiers have a few hard rules:
- They may contain letters, digits,
_and$, but cannot start with a digit. - They are case-sensitive:
totalandTotalare different. - Reserved words such as
class,returnandnewcannot be used.
Then there are conventions that teams expect:
camelCasefor variables and functions:orderTotal,getUser.PascalCasefor classes and constructor functions:ShoppingCart.UPPER_SNAKE_CASEfor true constants:MAX_RETRIES.- Booleans read as questions:
isOpen,hasAccess.
Choose names that say what something holds, not its type. users beats arr, and elapsedMs beats t. Good naming is part of every code review.
Practice. Rename every variable in a short, poorly named function so that the code reads without comments.
Variable Scopes: Global, Function and Block Core
Scope decides where a variable can be read. There are three main levels.
- Global scope: declared outside any function or block. Accessible everywhere, which makes accidental clashes likely. In modules, top-level variables are scoped to the module instead.
- Function scope: variables declared inside a function exist only there.
varrespects only this level. - Block scope:
letandconstlive only within the nearest pair of braces, such as anifor loop body.
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(b); // ReferenceErrorKeep variables in the smallest scope that works. The classic bug with var in loops, where every callback sees the final value, disappears with let, because each iteration gets a fresh binding.
Practice. Predict the output of a loop that schedules setTimeout callbacks with var and with let, then run both.
Hoisting Core
Hoisting describes how declarations are processed before code runs, so some names exist before the line that declares them.
- Function declarations are hoisted with their body; you can call them above their definition.
varis hoisted but initialised toundefined.let,constandclassare hoisted but not initialised. Touching them before the declaration throws aReferenceError. The gap between the start of the scope and the declaration is called the temporal dead zone.
sayHi(); // works
function sayHi() {}
console.log(x); // undefined
var x = 5;
console.log(y); // ReferenceError
let y = 5;Function expressions and arrow functions assigned to variables follow the rules of their variable. In practice, declare before use and the topic stops causing bugs, but expect it in interviews.
Practice. Write five short snippets that test hoisting rules and predict each result before running it.
Datatypes: Primitives Core
JavaScript has seven primitive datatypes plus objects.
string: text, written with single quotes, double quotes or backticks. Template literals in backticks allow${expression}and multiple lines.number: one type for integers and decimals, stored as 64-bit floating point. So0.1 + 0.2is not exactly0.3. Special values includeNaN,Infinityand-0.boolean:trueorfalse.undefined: a variable declared but not assigned, or a missing property.null: an intentional "no value", set by you.bigintandsymbol, covered next.
Primitives are immutable and compared by value. String methods such as toUpperCase return new strings; they never change the original. Safe integers go up to Number.MAX_SAFE_INTEGER; beyond that, precision is lost.
Practice. Write expressions that produce each primitive type and check them with typeof.
bigint and Symbol Recommended
bigint holds integers of any size. Create one with an n suffix or BigInt(). It suits IDs from databases, cryptography and exact large counts.
const big = 9007199254740993n;
big + 1n; // 9007199254740994n
big + 1; // TypeError: cannot mix BigInt and other typesYou cannot mix bigint and number in arithmetic without converting, and bigint division drops the remainder. JSON does not support it, so you convert to strings when sending data.
A Symbol is a unique value, mainly used as an object key that cannot clash with others. Symbol('id') === Symbol('id') is false. Well-known symbols such as Symbol.iterator let your objects plug into language features like for...of.
Practice. Compute 2 to the power 70 with number and with bigint and compare the results.
Object: Reference Types Core
Everything that is not a primitive is an Object: plain objects, arrays, functions, dates, maps. Objects are collections of properties and are passed around by reference.
const a = { score: 1 };
const b = a;
b.score = 2;
console.log(a.score); // 2: same object
console.log({} === {}); // false: different objectsTwo variables can point to the same object, so changing it through one is visible through the other. Equality compares references, not contents.
To copy, use spread { ...obj } or Object.assign for a shallow copy, and structuredClone(obj) for a deep copy. Many bugs in React and state management come from mutating shared objects, so this idea matters far beyond the basics.
Practice. Write a function that accidentally mutates its argument, then fix it by copying.
typeof operator Core
The typeof operator returns a string naming a value's type.
typeof 'hi' // 'string'
typeof 42 // 'number'
typeof 10n // 'bigint'
typeof undefined // 'undefined'
typeof null // 'object' (a historic bug)
typeof [] // 'object'
typeof (() => {}) // 'function'Two traps to remember. typeof null is 'object', a mistake from the first version that cannot be fixed, so check null with value === null. Arrays also report 'object'; use Array.isArray. For class instances use instanceof.
typeof is also safe on undeclared variables, returning 'undefined' instead of throwing, which is why older code used it for feature detection.
Practice. Write an describeType(value) function that correctly distinguishes null, arrays, functions and plain objects.
Stage 3 Expressions & Operators and Type Conversion
Goal. Combine values with operators and predict how JavaScript converts between types.
Arithmetic Operators and Assignment Operators Core
Arithmetic operators: +, -, *, /, % (remainder) and ** (exponent). Increment and decrement, ++ and --, come in prefix and postfix forms: ++i changes the value then returns it; i++ returns the old value then changes it.
Assignment operators store results: =, plus compound forms such as +=, -=, *= and **=. Logical assignment operators assign only under a condition:
let name;
name ??= 'Guest'; // assign if null or undefined
settings.debug ||= false;
total &&= total * 1.2; // assign if truthyDivision by zero gives Infinity, not an error, and invalid maths gives NaN. Check results with Number.isFinite or Number.isNaN.
Practice. Write a function that splits a bill between people and rounds to two decimals correctly.
Comparison Operators, Logical Operators and Conditional Operators Core
Comparison operators return booleans: <, >, <=, >=, ==, !=, === and !==. Comparing strings uses character codes, so '10' < '9' is true; use localeCompare for human sorting.
Logical operators &&, || and ! work with truthy and falsy values. Falsy values are false, 0, -0, 0n, '', null, undefined and NaN; everything else is truthy, including '0' and []. && and || return one of their operands, not a boolean, and stop evaluating early.
Conditional operators:
- The ternary
condition ? a : bpicks a value. - Nullish coalescing
??falls back only onnullorundefined, unlike||, which also replaces0and''. - Optional chaining
?.stops safely on null:user?.address?.city.
Practice. Rewrite a block of nested if checks for missing data using optional chaining and nullish coalescing.
Equality Comparisons: ==, ===, Object.is Core
JavaScript has several equality algorithms, and interviews love them.
===compares type and value with no conversion; the specification calls this isStrictlyEqual. Use it by default.==, which the specification calls isLooselyEqual, converts types first, with surprising results:0 == ''andnull == undefinedare both true.Object.isuses the SameValue algorithm: like===, exceptObject.is(NaN, NaN)is true andObject.is(0, -0)is false.- SameValueZero is what
includes,MapandSetuse: like SameValue, but treats0and-0as equal.
NaN === NaN // false
[NaN].includes(NaN) // trueOne accepted use of loose equality is value == null, which checks for both null and undefined. Objects under any of these are equal only if they are the same reference.
Practice. Build a table of ten value pairs and record the result of ==, === and Object.is for each.
String Operators, Unary Operators and Comma operators Recommended
String operators: + joins strings, and if either side is a string, the other is converted, so 1 + '2' is '12'. Template literals are clearer for building text.
Unary operators take one operand:
+valueconverts to a number;-valuenegates.!valuegives the boolean opposite;!!valueconverts to a boolean.typeof,delete(removes a property) andvoid(returnsundefined).
+'42' // 42
!!'' // false
delete obj.temp;Comma operators evaluate several expressions left to right and return the last. You will mostly see them in for loop headers, such as for (let i = 0, j = n; i < j; i++, j--), and in minified code. Elsewhere they hurt readability.
Practice. Predict the results of ten mixed + expressions with strings and numbers, then check them.
Bitwise Operators and BigInt Operators Optional
Bitwise operators work on the binary form of 32-bit integers: & (and), | (or), ^ (xor), ~ (not), << and >> (shifts) and >>> (unsigned shift). Their main uses are flags and permissions packed into one number, and low-level work with binary data.
const READ = 1, WRITE = 2, EXEC = 4;
let perms = READ | WRITE; // 3
const canWrite = (perms & WRITE) !== 0;BigInt operators are the usual arithmetic and bitwise operators applied to bigint values: +, -, *, **, / (rounds towards zero) and %. Unary + is not allowed on bigint, >>> is not supported, and both operands must be bigint. Comparisons such as 1n < 2 do work across types.
Practice. Store four on/off settings in one number using bit flags and write functions to toggle each.
Type Casting: Type Conversion, Coercion Core
Type conversion changes a value from one type to another. When you do it on purpose it is explicit type casting; when JavaScript does it for you, it is implicit type casting, usually called coercion.
Explicit conversion:
Number('42') // 42
Number('') // 0
parseInt('42px') // 42
String(10) // '10'
Boolean('false') // true: any non-empty stringImplicit conversion happens with + and strings, with ==, in if conditions and with arithmetic on non-numbers: '6' * '2' is 12, [] + {} is '[object Object]'. Objects convert by calling valueOf or toString.
Prefer explicit conversion at the edges of your program, such as form inputs and URL parameters, which are always strings. Then compare with === so no hidden conversion happens later.
Practice. Read numbers from two text inputs, convert them explicitly and show the sum, handling invalid input.
Stage 4 Control Flow and Error Handling
Goal. Direct program flow with conditions and loops and handle failures without crashing.
Control Flow: Conditional statements with if...else and Switch Core
Control flow is the order in which statements run. Conditional statements choose between paths.
if (score >= 70) {
grade = 'pass';
} else if (score >= 50) {
grade = 'retake';
} else {
grade = 'fail';
}A switch statement compares one value against several cases with strict equality. Each case needs a break, or execution falls through to the next case, which is occasionally useful and often a bug.
switch (status) {
case 'paid': ship(); break;
case 'pending': remind(); break;
default: log(status);
}Keep conditions readable: return early from functions to avoid deep nesting, and replace long switch statements that map values with an object or Map lookup.
Practice. Write a function that returns a shipping cost by country with if...else, then with switch, then with an object lookup.
Loops and Iterations: The for loop, while and do...while statement Core
Loops and iterations repeat work.
- The for loop has three parts: start, condition and step. Use it when you need the index.
- A
whileloop repeats as long as its condition is true, checked before each pass. - The
do...whilestatement checks after each pass, so its body always runs at least once, handy for "ask until valid" logic.
for (let i = 0; i < 3; i++) console.log(i);
let n = 10;
while (n > 1) n = n / 2;
do { input = ask(); } while (!isValid(input));Make sure every loop can end. For arrays, for...of and array methods such as map and filter are usually clearer than an index loop.
Practice. Write a number-guessing game in Node.js that loops until the user guesses correctly.
for...in loop and for...of statement Core
These two look alike but iterate different things.
- The
for...inloop walks the enumerable string keys of an object, including inherited ones. Use it rarely, and preferObject.keysorObject.entries. - The
for...ofstatement walks the values of any iterable: arrays, strings, maps, sets, generators and DOM collections.
const scores = { asha: 9, ben: 7 };
for (const [name, s] of Object.entries(scores)) {
console.log(name, s);
}
for (const ch of 'hey') console.log(ch);Using for...in on an array gives string indexes and may include extra properties, a common bug. Plain objects are not iterable, so for...of on them throws a TypeError.
Practice. Count the words in a sentence using for...of, storing counts in an object, then print them with Object.entries.
break, continue and Labels Recommended
break exits the nearest loop or switch immediately. continue skips the rest of the current pass and moves to the next one.
for (const order of orders) {
if (order.cancelled) continue; // skip this one
if (order.id === targetId) {
found = order;
break; // stop searching
}
}Labels let break or continue target an outer loop, which helps with nested searches:
outer: for (const row of grid) {
for (const cell of row) {
if (cell === 0) break outer;
}
}Note that break and continue do not work inside forEach callbacks. If you need to stop early, use a for...of loop or methods such as find and some.
Practice. Find the first pair of numbers in a list that sum to a target using nested loops and a labelled break.
Exception Handling: try, catch, finally, Throw Statement and Error Objects Core
Exception handling stops one failure from crashing everything. Wrap risky code in try; if something throws, control jumps to catch; finally runs either way, which suits clean-up.
function parseConfig(text) {
try {
return JSON.parse(text);
} catch (err) {
throw new Error('Invalid config', { cause: err });
} finally {
console.log('parse attempted');
}
}The throw statement can throw any value, but always throw Error objects: they carry a message, a name and a stack. Built-in error objects include TypeError, RangeError, SyntaxError and ReferenceError. Extend Error for your own types, and use the cause option to keep the original error.
Catch only what you can handle, and never swallow errors silently. Asynchronous errors need await inside the try, or a .catch() on the promise.
Practice. Write a ValidationError class and use it in a form validator, catching it separately from other errors.
Stage 5 Functions
Goal. Write clear functions and explain scope, closures and the call stack.
Functions: Declarations and Expressions Core
Functions are reusable blocks of code, and in JavaScript they are values: you can store them in variables, pass them as arguments and return them from other functions. This makes higher-order functions such as map possible.
function add(a, b) { return a + b; } // declaration, hoisted
const multiply = function (a, b) { return a * b; }; // expression
[1, 2, 3].map(n => n * 2); // passed as a valueA Function returns undefined unless it has an explicit return. Keep functions small and focused on one task, and name them with verbs.
There is also a Function constructor that builds functions from strings, similar to eval. Avoid it: it is slow, hard to debug and a security risk, and strict Content Security Policies block it.
Practice. Write a function that takes another function and calls it twice, then use it with three different functions.
Arrow Functions Core
Arrow functions are a shorter syntax, introduced in 2015, and they behave differently in important ways.
const square = x => x * x;
const toUser = (name, age) => ({ name, age }); // wrap object in ()
const log = () => { console.log('hi'); };A single expression body returns its value automatically. Differences from regular functions:
- They have no own
this; they use thethisof the surrounding code. That makes them ideal for callbacks inside methods. - They have no
argumentsobject; use rest parameters. - They cannot be used with
newand have noprototype.
Because of the this rule, do not use arrow functions as object methods that need to refer to the object.
Practice. Convert five callback functions to arrow functions and find one case where the conversion breaks the code.
Function Parameters: Default Parameters, Rest and the Arguments object Core
Function parameters are the names in the definition; arguments are the values passed in. JavaScript does not check counts: missing ones become undefined and extra ones are ignored.
Default parameters apply when the argument is undefined:
function greet(name = 'friend', greeting = `Hello`) {
return `${greeting}, ${name}`;
}
function sum(...nums) { // rest parameter
return nums.reduce((a, b) => a + b, 0);
}
function draw({ x = 0, y = 0 } = {}) {} // destructured optionsRest parameters gather remaining arguments into a real array. The older arguments object is array-like (no map), does not exist in arrow functions, and is rarely needed now. For functions with many options, accept one object and destructure it.
Practice. Write a formatPrice(amount, { currency = "GBP", decimals = 2 } = {}) function using defaults and destructuring.
Scope & Function Stack and Recursion Core
Each function call creates a new frame on the call stack, which holds its local variables and where to return. When the function returns, its frame is removed. This scope and function stack model explains error stack traces: they list the frames active when the error was thrown.
Recursion is a function calling itself. It needs a base case that stops, and each call must move towards it.
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}Recursion suits nested data, such as trees, menus and folder structures. Each call uses a stack frame, so very deep recursion throws RangeError: Maximum call stack size exceeded; JavaScript engines generally do not optimise tail calls. Convert to a loop with an explicit stack for very deep inputs.
Practice. Write a recursive function that sums all numbers in an arbitrarily nested array.
Lexical scoping and Closures Core
JavaScript uses lexical scoping: a function can see the variables where it was written, not where it is called.
A closure is a function together with the variables it captured from its surrounding scope. Those variables stay alive as long as the function does, even after the outer function has returned.
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2Closures power private state, factories, event handlers that remember data, memoisation, and React hooks. Their classic bug is a stale value: a callback captures a variable that later changes, or an old version in React. They can also keep large objects in memory longer than you expect.
Practice. Write a once(fn) helper that runs a function only the first time it is called, using a closure.
IIFEs Optional
An immediately invoked function expression, or IIFE, is a function that runs as soon as it is defined.
(function () {
const secret = 42; // not visible outside
})();
(async () => {
const data = await load();
})();Before block scope and modules, IIFEs were the main way to create private scope and avoid polluting the global namespace; you will see them in older libraries and in the "module pattern". Today, let, const and ES modules cover most of those needs. The async IIFE is still handy for running await in scripts that do not support top-level await.
Practice. Rewrite an old module-pattern IIFE as an ES module with exports.
Built in functions Recommended
JavaScript provides a number of built-in functions available everywhere through the global object (globalThis, which is window in browsers).
parseInt(str, 10)andparseFloat(str)read numbers from the start of a string. Always pass the radix toparseInt.isNaNandisFinitecoerce their argument first; preferNumber.isNaNandNumber.isFinite.encodeURIComponentanddecodeURIComponentmake text safe for URLs.setTimeout,setIntervalandqueueMicrotaskschedule work.structuredClonedeep-copies values.evalruns a string as code. Never use it with untrusted input; it is slow and dangerous.
parseInt('08', 10); // 8
encodeURIComponent('a&b c'); // 'a%26b%20c'
Practice. Build a query string from an object of filters using encodeURIComponent, then compare with URLSearchParams.
Stage 6 Objects, this, Prototypes and Classes
Goal. Model data with objects and classes and explain how this and prototypes really work.
Working with Objects Core
Objects map keys to values. Modern syntax makes them pleasant to work with.
const id = 7, field = 'role';
const user = { id, name: 'Asha', [field]: 'admin', greet() { return 'hi'; } };
const { name, role = 'guest' } = user; // destructuring
const updated = { ...user, name: 'Ben' }; // copy with changeUseful tools:
Object.keys,Object.valuesandObject.entrieslist contents;Object.fromEntriesbuilds objects back.inandObject.hasOwncheck for keys.- Property descriptors control whether a property is writable, enumerable or configurable;
Object.freezelocks an object shallowly. - Getters and setters compute values on access.
Optional chaining user?.profile?.email reads nested values safely.
Practice. Write a function that takes an array of products and returns an object grouped by category.
The this keyword: in a method, alone, in arrow functions and in event handlers Core
When you use the this keyword, remember that the call site sets its value, not the place the function was written, with arrow functions as the exception.
- this in a method: when called as
obj.method(),thisisobj. - Using it alone, at the top level: in a classic script it is the global object; in modules it is
undefined. - In a plain function call:
undefinedin strict mode, the global object otherwise. - In arrow functions: inherited from the surrounding scope, never set by the call.
- In event handlers: with
addEventListenerand a regular function,thisis the element the listener is attached to (same asevent.currentTarget). - With
new: the newly created object.
const counter = { n: 0, inc() { this.n++; } };
const inc = counter.inc;
inc(); // this is lost: undefined in strict modeLosing this when passing a method as a callback is the classic bug. Fix it with an arrow wrapper or bind.
Practice. Write four calls of the same function that each produce a different this, and explain each.
Explicit binding: call(), apply and bind() and Function Borrowing Core
Explicit binding sets this yourself.
fn.call(obj, a, b)calls immediately withthisasobjand arguments listed.fn.apply(obj, [a, b])is the same, with arguments as an array.fn.bind(obj, a)returns a new function withthisfixed permanently, and optionally some arguments preset.
function intro(greeting) { return `${greeting}, I am ${this.name}`; }
intro.call({ name: 'Asha' }, 'Hi');
const later = intro.bind({ name: 'Ben' }, 'Hello');
later();Function borrowing uses these to run a method from one object on another, for example Array.prototype.slice.call(arguments) in older code. Today Array.from and spread are clearer. bind remains common for passing methods as callbacks. Arrow functions ignore all three for this.
Practice. Implement your own simple version of bind using apply and a closure.
Prototypes and Prototypal Inheritance Core
Every object has an internal link to another object, its prototype. When you read a property that the object lacks, JavaScript looks along this prototype chain until it finds it or reaches null. That is prototypal inheritance.
const animal = { speak() { return `${this.name} makes a sound`; } };
const dog = Object.create(animal);
dog.name = 'Rex';
dog.speak(); // found on animal
Object.getPrototypeOf(dog) === animal; // trueFunctions have a prototype property; objects made with new Fn() link to it. That is how [].map works: arrays link to Array.prototype. Classes are syntax on top of this same mechanism.
Do not change built-in prototypes such as Array.prototype in your own code; it causes conflicts with libraries and future language features.
Practice. Draw the prototype chain of an array, a function and an object created with Object.create(null).
Classes Core
Classes give a clear syntax for constructor functions and prototypes.
class Account {
#balance = 0; // private field
static count = 0;
constructor(owner) { this.owner = owner; Account.count++; }
deposit(amount) {
if (amount <= 0) throw new RangeError('Amount must be positive');
this.#balance += amount;
}
get balance() { return this.#balance; }
}
class Savings extends Account {
constructor(owner, rate) { super(owner); this.rate = rate; }
}Key points: methods live on the prototype; extends sets up inheritance and super calls the parent; fields starting with # are truly private; static members belong to the class itself. Class bodies run in strict mode and classes are not hoisted for use. Prefer composition over deep inheritance chains.
Practice. Model a library with Book, Member and Loan classes, using private fields and validation.
Built-in Objects Recommended
The language ships with built-in objects you will use constantly.
Math:Math.round,Math.max,Math.random(not for security; usecrypto.getRandomValues).Date: dates and times, with a confusing API and months counted from 0. The newerTemporalAPI is arriving in engines; until it is everywhere, libraries help.Intl: formatting numbers, currencies, dates and lists for any locale, such asnew Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' }).RegExp: regular expressions for pattern matching.Promise,Map,Set,ErrorandJSON, covered in their own topics.Number,StringandBooleanwrappers provide methods for primitives.
Learning Intl saves you from hand-written formatting bugs.
Practice. Format the same price and date for British, German and Japanese users with Intl.
JSON and Structured Data Core
JSON is a text format for structured data, based on JavaScript object syntax but stricter: keys need double quotes, and there are no functions, undefined, comments or trailing commas.
const text = JSON.stringify({ id: 1, tags: ['a'] }, null, 2);
const data = JSON.parse(text);JSON.stringify drops functions and undefined, turns Date into strings and throws on circular references and bigint. JSON.parse throws on invalid input, so wrap it in try...catch when the text comes from outside. Both accept a function to customise conversion.
JSON is how most APIs exchange data. For copying structured data inside your program, structuredClone handles dates, maps, sets and cycles, which a JSON round-trip does not.
Practice. Save an app state object to localStorage as JSON and restore it, keeping dates as Date objects.
Stage 7 Data Structures and Iteration
Goal. Pick the right built-in collection and process data with array methods and iterators.
Data Structures: Indexed collections and Arrays Core
JavaScript's built-in data structures fall into two families: indexed collections, ordered by number (arrays and typed arrays), and keyed collections (maps and sets).
Arrays hold ordered lists of any values and grow as needed.
const nums = [3, 1, 2];
nums.push(4); // add at end
nums.at(-1); // 4, last item
nums.includes(2); // true
const [first, ...rest] = nums;Know which methods change the array in place and which return a new one. push, pop, shift, splice, sort and reverse mutate. slice, concat, spread and the newer toSorted, toReversed and with return copies, which suits frameworks that need immutable updates. Remember that sort compares as strings by default: pass (a, b) => a - b for numbers.
Practice. Write functions that add, remove and update an item in an array without mutating the original.
Array Methods: map, filter, reduce and Friends Core
Higher-order array methods replace most manual loops.
maptransforms each item into a new array.filterkeeps items that pass a test.reducefolds the array into one value, such as a total or an object.findandfindIndexreturn the first match;someandeverytest conditions.flatandflatMapflatten nested arrays.forEachruns side effects and returns nothing.
const total = cart
.filter(item => item.inStock)
.map(item => item.price * item.qty)
.reduce((sum, x) => sum + x, 0);Always pass an initial value to reduce. Chained methods are readable but loop several times; that is fine for typical sizes. Object.groupBy groups items by a key in current engines.
Practice. Given an array of orders, compute revenue per customer with filter, map and reduce.
Keyed Collections: Map and Set Core
Keyed collections store values by key or by uniqueness.
A Map stores key and value pairs where keys can be any type, including objects. It keeps insertion order, has a size and is built for frequent additions and deletions.
const visits = new Map();
visits.set('/home', (visits.get('/home') ?? 0) + 1);
for (const [path, n] of visits) console.log(path, n);A Set stores unique values. [...new Set(list)] removes duplicates. Current engines add set methods such as union, intersection and difference.
Use a plain object for fixed, known fields, such as a record from JSON. Use a Map for dictionaries built at runtime, especially with non-string keys. Both use SameValueZero to compare keys.
Practice. Find the words that appear in both of two paragraphs using Set, and count word frequency with Map.
Weak Map and Weak Set Optional
WeakMap and WeakSet, the weak map and weak set, hold objects without preventing them from being garbage collected. When nothing else refers to a key object, its entry can disappear.
const metadata = new WeakMap();
function track(el) {
metadata.set(el, { clicks: 0 });
}
// when el is removed from the DOM and dropped, its data can be collectedKeys must be objects (or non-registered symbols). They are not iterable and have no size, because their contents can change at any moment as collection happens.
They suit caches and private data attached to objects you do not own, such as DOM nodes, without causing memory leaks. For advanced cases, WeakRef and FinalizationRegistry exist, but they are rarely the right tool.
Practice. Cache an expensive computation per object with a WeakMap and explain why a Map would leak.
Typed Arrays Optional
Typed arrays are fixed-length arrays of raw binary numbers of one type, such as Uint8Array, Int32Array and Float64Array. They are views over an ArrayBuffer, a block of raw memory.
const buf = new ArrayBuffer(8);
const bytes = new Uint8Array(buf);
bytes[0] = 255;
bytes[1] = 256; // wraps to 0They are used for performance-sensitive and binary work: reading files, images on a canvas, audio, WebGL, WebAssembly and network protocols. fetch responses can be read as an ArrayBuffer, and TextEncoder and TextDecoder convert between strings and bytes.
Most application code never needs them, but you should recognise them when an API returns binary data.
Practice. Read a small image file with the File API into a Uint8Array and print its first eight bytes.
JavaScript Iterators and Generators Recommended
An iterator is an object with a next() method returning { value, done }. An iterable is any object with a Symbol.iterator method that returns one. Arrays, strings, maps, sets and many DOM lists are iterable, which is what for...of, spread and destructuring use.
Generators make iterators easy. A function* pauses at each yield and resumes when asked for the next value.
function* range(start, end, step = 1) {
for (let i = start; i < end; i += step) yield i;
}
[...range(0, 10, 3)]; // [0, 3, 6, 9]Generators are lazy, so they can describe infinite sequences. Async generators with for await...of consume streams of data, such as paginated API results. Newer iterator helpers like map and take are arriving on iterators directly.
Practice. Write a generator that yields Fibonacci numbers forever and take the first 20 lazily.
Stage 8 Asynchronous JavaScript
Goal. Write and debug asynchronous code and explain the event loop with confidence.
Asynchronous JavaScript and the Event Loop Core
JavaScript runs your code on a single thread. Slow work such as network requests and timers is handled by the browser or Node.js, which queue a callback when it finishes. The event loop decides when those callbacks run.
The order is:
- Run the current script until the call stack is empty.
- Run every queued microtask: promise callbacks,
awaitcontinuations andqueueMicrotask. - In the browser, render if needed.
- Take one task (macrotask), such as a timer, an event or a message, and repeat.
console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => console.log(3));
console.log(4);
// 1, 4, 3, 2Long synchronous work blocks everything, including clicks and painting. Split heavy work into chunks or move it into a Web Worker.
Practice. Predict the output order of a snippet mixing setTimeout, promises and await, then run it.
setTimeout and setInterval Core
setTimeout(fn, ms) runs a function once after at least ms milliseconds. setInterval(fn, ms) runs it repeatedly. Both return an ID you pass to clearTimeout or clearInterval to cancel.
const id = setTimeout(() => save(draft), 500);
clearTimeout(id); // cancel if the user types again
let ticks = 0;
const timer = setInterval(() => {
if (++ticks === 5) clearInterval(timer);
}, 1000);The delay is a minimum, not a guarantee: the callback waits for the call stack to be free. Browsers slow timers in background tabs. setInterval does not wait for slow work to finish, so a chained setTimeout is safer for polling. Always clear timers when a component or page section is removed. For animation, use requestAnimationFrame.
Practice. Build a debounce function with setTimeout and use it on a search input.
Callbacks and Callback Hell Core
A callback is a function passed to another function to be called later, when the work is done. It is the original way to handle asynchronous results, and it is still used for events and timers.
readFile('a.txt', (err, a) => {
if (err) return handle(err);
readFile('b.txt', (err, b) => {
if (err) return handle(err);
save(a + b, (err) => { /* … */ });
});
});Nesting dependent steps like this produces callback hell: code that drifts to the right, repeats error handling at every level, and is hard to follow or change. Node.js used an "error-first" convention, where the first argument is the error. Promises and async/await were introduced largely to fix this, and Node's core modules offer promise versions such as fs/promises.
Practice. Write three dependent steps with nested callbacks, then rewrite them with promises.
Promises Core
A promise represents a value that will be available later. It is pending, then either fulfilled with a value or rejected with an error, and it settles only once.
fetchUser(1)
.then(user => fetchOrders(user.id))
.then(orders => render(orders))
.catch(err => showError(err))
.finally(() => hideSpinner());Each then returns a new promise, so steps chain without nesting, and one catch handles errors from any step. Combinators run several promises:
Promise.allwaits for all and fails fast on the first rejection.Promise.allSettledwaits for all and reports each outcome.Promise.racesettles with the first to settle;Promise.anywith the first to succeed.
Always return promises from then callbacks and handle rejections; unhandled ones are reported as errors.
Practice. Wrap setTimeout in a delay(ms) function that returns a promise and chain three delays.
Async/Await Core
async and await let you write promise code that reads top to bottom. An async function always returns a promise; await pauses that function until a promise settles, without blocking the thread.
async function loadDashboard(id) {
try {
const user = await getUser(id);
const [orders, alerts] = await Promise.all([
getOrders(user.id), getAlerts(user.id),
]);
return { user, orders, alerts };
} catch (err) {
report(err);
throw err;
}
}Errors are handled with normal try...catch. A common mistake is awaiting independent calls one after another; start them together with Promise.all. Another is await inside forEach, which does not wait; use for...of or Promise.all with map. Modules support top-level await.
Practice. Convert a promise chain to async/await, then make two independent requests run in parallel.
Fetch and Working with APIs Core
Working with APIs mostly means fetch, which returns a promise of a Response.
async function getJson(url, { signal } = {}) {
const res = await fetch(url, { signal, headers: { Accept: 'application/json' } });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
await fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Pen' }),
});fetch rejects only on network failure; a 404 or 500 still fulfils, so check res.ok. Use AbortController to cancel stale requests and set timeouts. Requests to other origins are subject to CORS, which the server controls. XMLHttpRequest is the older API you may meet in legacy code; it uses events instead of promises, and new code should use fetch.
Practice. Build a search box that fetches results, shows loading and error states, and aborts the previous request on each keystroke.
Stage 9 The Browser: DOM, Events and Modules
Goal. Update pages through the DOM, handle events efficiently and organise code into modules.
DOM APIs Core
The DOM is the browser's tree of objects for the page. DOM APIs let you find, read, create and change elements.
const list = document.querySelector('#todos');
const item = document.createElement('li');
item.textContent = 'Buy milk';
item.classList.add('todo');
list.append(item);
document.querySelectorAll('.done').forEach(el => el.remove());Key methods: querySelector and querySelectorAll to find elements, textContent to set text safely, classList to toggle classes, dataset for data attributes, setAttribute, and append, remove and replaceWith to change structure.
Avoid innerHTML with user input; it allows script injection. Reading layout values such as offsetHeight right after writing styles forces extra layout work, so batch reads and writes.
Practice. Build a to-do list that adds, completes and removes items using only DOM APIs.
Events and Event Delegation Core
Events notify your code when something happens: clicks, key presses, form submission, scrolling. Attach handlers with addEventListener.
form.addEventListener('submit', (e) => {
e.preventDefault(); // stop the page reload
save(new FormData(form));
});
list.addEventListener('click', (e) => {
const btn = e.target.closest('button.delete');
if (btn) btn.closest('li').remove();
});Most events bubble from the target up through its ancestors. Event delegation uses this: one listener on a parent handles events from many children, including ones added later. event.target is where the event started; event.currentTarget is where the listener sits. stopPropagation stops bubbling, but use it sparingly. Options such as { once: true }, { passive: true } and signal help with clean-up and scroll performance.
Practice. Rewrite a page with a click listener on every row so that one delegated listener handles all rows.
Modules: ESModules and CommonJS Core
Modules split code into files with their own scope and explicit imports and exports.
ESModules are the standard, supported in browsers and Node.js:
// math.js
export function add(a, b) { return a + b; }
export default function mean(xs) { return xs.reduce(add, 0) / xs.length; }
// app.js
import mean, { add } from './math.js';
const { chart } = await import('./chart.js'); // loaded on demandCommonJS is Node's original system, using require and module.exports. It loads synchronously and is still common in older packages. Node decides which system a file uses from the .mjs or .cjs extension or the type field in package.json.
ES modules are static, so bundlers can remove unused exports (tree shaking). Prefer named exports for clearer imports and refactoring.
Practice. Split a single-file app into four ES modules and lazy-load one of them with dynamic import().
Strict Mode Recommended
Strict mode is a stricter dialect you choose to enable. It turns silent mistakes into errors and removes some confusing features. Enable it with 'use strict'; at the top of a script or function.
What it changes:
- Assigning to an undeclared variable throws instead of creating a global.
thisisundefinedin plain function calls instead of the global object.- Writing to read-only properties throws.
- Duplicate parameter names and the
withstatement are not allowed.
ES modules and class bodies are always in strict mode, so most modern code already uses it without the directive. You will still see 'use strict' at the top of older scripts and Node files using CommonJS.
Practice. Run a snippet with an accidental global assignment with and without strict mode and compare the results.
Browser Storage and Other Web APIs Recommended
Browsers expose many APIs beyond the DOM. The ones most front-end jobs touch:
localStorageandsessionStorage: small string key and value stores, synchronous, per origin. Store JSON strings; never store tokens that attackers could steal through script injection.- Cookies: sent with requests; use
HttpOnly,SecureandSameSiteset by the server for sessions. - IndexedDB: an asynchronous database for larger structured data and offline apps.
URLandURLSearchParamsfor parsing and building addresses.IntersectionObserverandResizeObserverto react to visibility and size without polling.- Web Workers to run heavy code off the main thread.
Check support and permissions for newer APIs, and wrap storage calls in try...catch, since they can fail in private browsing.
Practice. Lazy-load images with IntersectionObserver and remember a theme choice in localStorage.
Stage 10 Memory, Debugging and Performance
Goal. Find and fix bugs, memory leaks and slow code using browser tools.
Memory Management and the Memory Lifecycle Recommended
JavaScript manages memory for you, but you still need to understand it. The memory lifecycle has three steps: allocate when you create values, use them by reading and writing, and release when they are no longer needed. The first two happen automatically when you create objects, arrays and closures; the third is done by the garbage collector.
Memory management problems come from keeping references you no longer need. Anything reachable from a root, such as global variables, the current call stack or active listeners, stays alive. Primitives in local variables are cheap; large arrays, DOM nodes and caches are where memory goes.
In long-lived pages and Node servers, small leaks add up until the tab slows or the process crashes, so memory is a common senior interview topic.
Practice. Use the Memory panel to compare heap size before and after creating and discarding a large array.
Garbage Collection Recommended
Garbage collection finds memory that can no longer be reached and frees it. Modern engines use mark-and-sweep: starting from roots such as globals and the stack, they mark every object they can reach and sweep away the rest. Unreachable cycles, such as two objects pointing at each other, are therefore collected, unlike simple reference counting.
Engines like V8 split the heap into generations: most objects die young, so a fast collector cleans new objects often and a slower one handles long-lived ones. Collection runs automatically; you cannot trigger it from normal code, and pauses are usually short.
What you control is reachability. Drop references you no longer need, remove listeners, clear timers, and use WeakMap for data attached to objects with their own lifetime.
Practice. Write a short explanation, with a diagram, of why two objects referring to each other are still collected.
Using Browser DevTools Core
Using browser DevTools well is the fastest way to understand and fix JavaScript.
- Console: run code, inspect objects, and use
console.table,console.timeandconsole.trace. - Sources: set breakpoints, step through code line by line, watch expressions and inspect the call stack and scope. Conditional breakpoints and logpoints avoid editing code. The
debuggerstatement pauses at that line. - Network: see every request, its timing, headers and response; throttle to simulate slow networks.
- Performance: record a session to see long tasks, layout and paint.
- Memory: take heap snapshots and track allocations.
- Application: inspect storage, cookies and service workers.
Node.js can be debugged with the same tools by running node --inspect.
Practice. Fix a bug in a small app using only breakpoints and the Scope panel, without adding console.log.
Debugging Issues Core
Debugging issues is a skill you can follow step by step:
- Reproduce the bug reliably and write down the exact steps.
- Read the error: message, type and stack trace tell you what failed and where.
- Narrow it down: use breakpoints or binary search through recent changes, for example with
git bisect. - Form a hypothesis and test it, rather than changing code at random.
- Fix the cause, not the symptom, and add a test that would have caught it.
Common JavaScript causes: undefined from a typo or missing data, this lost in a callback, mutation of shared objects, unhandled promise rejections, and await missing so code runs before data arrives. Source maps let you debug the original code after bundling and minification.
Practice. Take a bug report from an open project or a friend, and record each debugging step you take to fix it.
Debugging Memory Leaks Recommended
Debugging memory leaks starts with the usual suspects:
- Event listeners added repeatedly and never removed.
- Timers from
setIntervalthat keep running after their view is gone. - Detached DOM nodes still referenced from JavaScript.
- Caches and maps that grow forever.
- Closures holding large objects longer than needed.
- Accidental globals.
To find them, use the Memory panel: take a heap snapshot, perform an action several times, take another and compare. Look for object counts that keep growing and for "Detached" DOM trees, then follow the retainers chain to see what holds them.
Fixes include removing listeners or using an AbortController signal, clearing timers, bounding caches, and using WeakMap or WeakRef where data should not keep objects alive.
Practice. Create a page that leaks by adding listeners on every open of a panel, find it with heap snapshots, and fix it.
Debugging performance Recommended
For debugging performance, measure before you change anything. In the Performance panel, record the slow interaction and look for long tasks (over 50 ms), forced layouts and heavy scripts. Interaction to Next Paint measures how quickly the page responds to input and is the Core Web Vital most affected by JavaScript.
Common fixes:
- Debounce or throttle frequent events such as scroll, resize and input.
- Batch DOM reads and writes to avoid layout thrashing.
- Break long tasks into chunks, yield to the main thread, or move work into a Web Worker.
- Load less code: split bundles and lazy-load with dynamic
import(). - Use better algorithms and data structures, such as a
Setlookup instead of nested loops.
performance.now() and console.time give quick timings during development.
Practice. Profile a slow list filter, find the hot function and make it at least five times faster.
Projects to build
Build these in order. Each one should end up in a public repository with a short README that explains your decisions.
- Tip calculator and unit converterBeginner
Build a small page that reads values from inputs, converts them explicitly, validates them and shows results as you type. Format currencies with
Intland handle empty and invalid input gracefully.Variables and types · Type conversion · Conditional statements · DOM APIs · Events
- To-do app with persistenceBeginner
Build a to-do list with add, edit, complete, delete and filter. Use event delegation, store tasks in
localStorageas JSON, and keep all state in one array that you update without mutation.Arrays · Array methods · JSON · Event delegation · Browser storage
- Weather or film searchIntermediate
Build a search app on a free public API. Debounce the input, cancel stale requests with
AbortController, show loading, empty and error states, and cache recent results in aMap. Split the code into ES modules.Fetch · Async/await · Error handling · Map · Modules
- Quiz engine with classesIntermediate
Create a quiz app with
Quiz,QuestionandTimerclasses, private fields, a countdown withsetInterval, randomised questions and a results screen. Write unit tests for the scoring logic.Classes · Closures · setInterval · Exception handling · Testing
- Infinite-scroll image galleryAdvanced
Build a gallery that loads pages of images with an async generator, renders them lazily with
IntersectionObserver, and opens a detail view. Profile it, fix any long tasks, and prove with heap snapshots that it does not leak memory after many pages.Iterators and generators · Promises · Web APIs · Debugging performance · Debugging memory leaks
Interview questions
Try to answer each question out loud before you open the answer.
What is the difference between let, const and var?Junior
var is function-scoped, can be redeclared, and is hoisted with the value undefined, so it can be used before its line without an error. let and const are block-scoped and sit in the temporal dead zone until declared, so early access throws. const cannot be reassigned, though an object it points to can still change. I use const by default, let when I need to reassign, and avoid var in new code.
What is the difference between == and ===?Junior
=== compares value and type with no conversion, so 1 === '1' is false. == converts operands to a common type first, so 1 == '1' is true, along with surprises like 0 == ''. I use === everywhere, with one common exception: value == null to check for both null and undefined. Neither handles NaN well; NaN === NaN is false, so I use Number.isNaN or Object.is.
What is the difference between null and undefined?Junior
undefined means a value was never assigned: an uninitialised variable, a missing property, a missing argument or a function with no return. null is a value a programmer sets on purpose to say "nothing here". typeof undefined is 'undefined', while typeof null is 'object' because of an old bug. JSON supports null but drops undefined. Nullish coalescing ?? treats both as missing.
What is hoisting?Junior
Before running code in a scope, the engine registers its declarations. Function declarations are available in full, so you can call them before their line. var variables exist but hold undefined until assigned. let, const and classes are registered but not initialised, so using them before the declaration throws a ReferenceError, the temporal dead zone. In practice I declare things before use, which makes hoisting irrelevant to how the code reads.
What is a closure? Give a practical use.Mid
A closure is a function that keeps access to variables from the scope where it was created, even after that scope has finished. For example, a makeCounter function returns an inner function that increments a private count; each counter has its own copy. Practical uses are private state, function factories, memoisation, debounce helpers and event handlers that remember data. The pitfalls are stale values captured too early and memory kept alive longer than expected.
How is this determined in JavaScript?Mid
The call site decides it. As obj.method(), this is obj. As a plain call, it is undefined in strict mode or the global object otherwise. With new, it is the new object. With call, apply or bind, it is whatever you pass. Arrow functions have no own this and use the surrounding one. In addEventListener handlers written as regular functions, it is the element. The classic bug is passing a method as a callback and losing its this.
Explain the event loop and the difference between microtasks and macrotasks.Mid
JavaScript runs one call stack. When it empties, the event loop first drains the microtask queue, which holds promise callbacks, await continuations and queueMicrotask jobs, including any new ones added along the way. Then the browser may render, and the loop takes one macrotask, such as a timer callback, an event or a message, and repeats. That is why a resolved promise's then runs before a setTimeout of 0, and why an endless chain of microtasks can freeze rendering.
What are promises, and how do Promise.all and Promise.allSettled differ?Mid
A promise is an object for a value that will arrive later; it is pending, then fulfilled or rejected, once. then chains steps and catch handles errors from any earlier step. Promise.all takes several promises and fulfils with all results in order, but rejects as soon as any one rejects. Promise.allSettled always waits for all of them and gives each outcome with its status, which suits cases where partial success is acceptable, such as loading optional dashboard widgets.
How does prototypal inheritance work, and how do classes relate to it?Mid
Each object links to a prototype. When a property is not found on the object, the engine looks up the chain until it finds it or reaches null. Arrays get map from Array.prototype this way. Classes are syntax on top: methods go on the class's prototype object, extends links one prototype to another, and super calls the parent. Private fields, static members and strict mode by default are the main things classes add beyond syntax.
What is event delegation and why use it?Mid
Event delegation attaches one listener to a common ancestor instead of one per child. Because most events bubble, the ancestor receives events from its descendants, and I use event.target.closest(selector) to find which child was used. It means fewer listeners, less memory, and it works for elements added later, which suits lists and tables rendered dynamically. I check that the matched element is inside the container, and avoid it for events that do not bubble, such as focus, where focusin works instead.
What is the difference between call, apply and bind?Mid
All three set this explicitly. call invokes the function immediately with arguments listed one by one. apply invokes it immediately with arguments as an array. bind does not invoke; it returns a new function with this, and optionally some leading arguments, fixed permanently. I use bind most, for passing methods as callbacks, though an arrow wrapper often reads better. None of them change this for arrow functions.
What causes memory leaks in JavaScript, and how do you find them?Senior
Leaks happen when references keep unneeded objects reachable: listeners never removed, intervals never cleared, detached DOM nodes referenced from code, caches that only grow, closures holding big data, and accidental globals. To find one, I reproduce the action several times, take heap snapshots before and after in the Memory panel, compare them for growing object counts and detached nodes, then follow the retainer path. Fixes are cleanup with AbortController signals, clearing timers, bounded caches and WeakMap for attached data.
How would you make a slow, janky page more responsive?Senior
First I measure with the Performance panel and field data for Interaction to Next Paint, to find the long tasks behind the interaction. Then I fix the causes: debounce frequent handlers, batch DOM reads and writes to avoid forced layout, split long tasks and yield back to the main thread, move heavy computation to a Web Worker, and reduce the JavaScript loaded with code splitting. I also check algorithms, since an accidental quadratic loop is common. Then I measure again.
Compare ES modules and CommonJS.Senior
ES modules use import and export, are the language standard, work in browsers and Node, load asynchronously and have static structure, which lets bundlers tree-shake unused code. They support top-level await and run in strict mode. CommonJS uses require and module.exports, loads synchronously and is resolved at runtime, so imports can be conditional. Node chooses the system from file extensions or package.json. Mixing them has rough edges; new code should use ES modules.
Implement a debounce function and explain when you would use it.Senior
Debounce delays running a function until calls have stopped for a set time. It uses a closure over a timer ID:
function debounce(fn, ms) {
let id;
return function (...args) {
clearTimeout(id);
id = setTimeout(() => fn.apply(this, args), ms);
};
}I use it for search-as-you-type, auto-save and resize handlers, where only the final value matters. Throttle is the alternative when I need regular updates during activity, such as scroll position.
Common mistakes
- Using
==and relying on coercion; use===and convert types explicitly at the edges. - Mutating shared objects and arrays by accident; copy with spread or
structuredClone, or use non-mutating methods liketoSorted. - Forgetting to check
response.okafterfetch, so HTTP errors look like success; throw when it is false. - Awaiting independent requests one by one; start them together and use
Promise.all. - Using
awaitinsideforEachand expecting it to wait; usefor...oforPromise.allwithmap. - Losing
thiswhen passing a method as a callback; use an arrow wrapper orbind. - Leaving promise rejections unhandled; add
catchortry...catcharound every awaited call that can fail. - Using
innerHTMLwith user input; settextContentor build elements with DOM APIs. - Adding listeners and intervals without removing them; clean up with
removeEventListener,clearIntervalor anAbortControllersignal.
Ready-for-interview checklist
- I can explain each data type, including why
typeof nullis"object". - I can predict the result of coercion and equality questions and explain
Object.is. - I can explain scope, hoisting and the temporal dead zone.
- I can write and explain closures and use them for private state.
- I can explain how
thisis set in every calling pattern, and usecall,applyandbind. - I can explain prototypes and write classes with inheritance and private fields.
- I can choose between arrays, objects,
MapandSetand use the main array methods fluently. - I can explain the event loop and predict the order of timers, promises and
await. - I can write async code with proper error handling, parallel requests and cancellation.
- I can build an interactive page with DOM APIs and event delegation.
- I can organise code into ES modules and explain how they differ from CommonJS.
- I can use breakpoints, the Network panel and heap snapshots to debug real problems.
- I can write debounce and throttle from scratch.
Related roadmaps
- TypeScript RoadmapTypes, generics, narrowing, utility types and project setup.
- Node.js RoadmapEvent loop, modules, HTTP, streams, frameworks and deployment.
- React RoadmapComponents, hooks, state, data fetching, performance and testing.
- HTML RoadmapSemantic structure, forms, media, accessibility and SEO basics.
- CSS RoadmapCascade, layout with flexbox and grid, responsive design, animation.
- Data Structures and Algorithms RoadmapFrom arrays to graphs and DP, organised by interview pattern.
FAQ
How long does it take to learn JavaScript?
Most people can write simple scripts within a month. Reaching the level expected in a junior front-end interview, including async code, the DOM, closures and debugging, usually takes three to four months at about eight hours a week. Building small projects throughout is what makes it stick.
Should I learn JavaScript or TypeScript first?
JavaScript first. TypeScript adds static types on top of JavaScript and compiles to it, so every runtime behaviour, from closures to the event loop, is still JavaScript. Once you are comfortable with this roadmap, the TypeScript Roadmap roadmap is the natural next step, and most teams expect it.
Do I need to learn JavaScript before React?
Yes. React is mostly plain JavaScript: arrays, objects, closures, modules, promises and reference equality. Many problems that look like React bugs are JavaScript gaps. Finish at least the functions, objects, data structures and async stages here before starting the React Roadmap roadmap.
Is JavaScript good for back-end development?
Yes. Node.js runs JavaScript on servers and is widely used for APIs, real-time apps and tooling. Using one language across front end and back end is a real advantage for small teams. The Node.js Roadmap roadmap covers the server side.
How do I practise for JavaScript coding interviews?
Practise output-prediction questions on coercion, hoisting, closures, this and the event loop, and implement utilities such as debounce, deep clone, bind and a simple promise-based queue from scratch. Pair that with data structure and algorithm problems in JavaScript in coding practice, and explain your reasoning out loud as you work.