Learn JavaScript With a Roadmap From Script to Production
Learn JavaScript in order: twelve stages from a first script to a tested, deployable program, each with a worked exercise, its output and an exit check.

Most people who try to learn JavaScript stall in one of two places. Some work through tutorial after tutorial and can follow every example but cannot start a program from a blank file. Others jump into a framework in the first week and learn a pile of conventions with no idea which part is the language and which is the library. This guide is a fix for both. It is a sequence of twelve stages that takes you from a first script to a tested program that runs as a small service, and every stage has the same four parts: what to learn, a worked exercise with its exact output, a project you should write yourself, and a way to tell that you are ready to move on.
The order is deliberate. Each stage uses only what the stages before it taught, so you are never asked to type something you cannot yet read. Stages one to four are the core of the language and are where most of the time should go. Stages five to eight are the ideas that cause the most confusion later: errors, scope, modern syntax and asynchronous code. Stages nine to twelve move from exercises to programs: reading files and arguments, tests, tools, and the habits that make code safe to run for other people. The code runs on Node.js 24 as .mjs files, so you need nothing but a terminal and an editor. The complete guide to modern JavaScript is the reference to keep open next to this one.
How to use this roadmap
Read the stage, then close the page and write the exercise from memory before you compare. A stage is finished when you can write its project without looking at the text, not when you have read it. If you can only follow along, you have learned to recognize code, which is a different skill from writing it, and the gap shows up the first time you face a blank file.
Four habits carry through every stage.
Type the code. Copying and pasting skips the part of the brain that learns. Typing an example, getting a syntax error because of a missing bracket and finding the bracket is the lesson.
Run it after every small change. A program that grows for twenty lines before its first run has twenty places for a mistake. Change one thing, run, read the output, and move on.
Predict before you run. Before pressing enter, say what the output will be. When the prediction is wrong, you have found a gap in your model, and that is the most useful event in a learning session.
Change one thing on purpose to break it. Delete a bracket, swap a let for a const, pass a string instead of a number. Read the error message and say what it means. Errors are the language explaining itself, and stage five is about learning to read them.
The roadmap leaves out a few things on purpose, and the boundary section at the end lists them. The short version: it teaches JavaScript the language and the Node.js runtime, and it does not teach a front-end framework, a database or algorithms.
| Stage | Topic | You can finish it when you can |
|---|---|---|
| 1 | Values, variables, operators | Write a script that reads values and prints a calculated result |
| 2 | Decisions and loops | Solve a small puzzle with if, for and while |
| 3 | Functions | Split a program into functions that each do one thing |
| 4 | Arrays and objects | Model a list of records and summarize it |
| 5 | Errors and debugging | Read an error message and find its cause in a few minutes |
| 6 | Scope, closures and this | Explain why a callback sees the variable it sees |
| 7 | Modern syntax and modules | Split a project across files and use destructuring and spread |
| 8 | Asynchronous code | Write code that waits for something and handles its failure |
| 9 | Files, arguments and the platform | Build a command-line tool that reads a file |
| 10 | Tests | Write a test before the function it checks |
| 11 | Tools | Set up a project with a linter, a formatter and scripts |
| 12 | Production habits | Run a small server and make it safe to leave running |
Stage 1: values, variables and operators
Install Node.js 24 from nodejs.org, create a folder, and put a file in it named tip.mjs. Run it from the terminal with node tip.mjs. The .mjs extension tells Node.js to treat the file as an ES module, the format the rest of this guide uses. The first things to learn are the values a program holds, the names it gives them and the operators that combine them.
Values come in a small set of types: numbers, strings, booleans, undefined, null, bigint and symbol, plus objects. You will use the first four constantly in this stage. A variable is a name for a value, declared with const when the name will not point at anything else and let when it will. Do not use var, which older tutorials teach, because its scoping rules cause bugs that let and const do not.
const bill = 84.5;
const tipPercent = 18;
const people = 3;
const tip = (bill * tipPercent) / 100;
const total = bill + tip;
const perPerson = total / people;
console.log(`Tip: ${tip.toFixed(2)}`);
console.log(`Total: ${total.toFixed(2)}`);
console.log(`Each pays: ${perPerson.toFixed(2)}`);Tip: 15.21
Total: 99.71
Each pays: 33.24The arithmetic operators are +, -, *, / and %, the remainder. The text between backticks is a template literal, which puts the value of each ${...} into the string. toFixed(2) turns a number into text with two decimal places. console.log prints its argument and is your main tool for seeing what a program is doing, so use it freely.
Two rules from this stage save a great deal of trouble later. First, numbers in JavaScript are binary floating-point values, so some decimal fractions cannot be stored exactly, and 0.1 + 0.2 is 0.30000000000000004. That is why the example formats its results, and why money in a real program is kept as whole cents. Why 0.1 + 0.2 is not 0.3 explains the mechanism. Second, the + operator adds numbers and joins text, so "5" + 3 is "53", not 8. When a value arrives as text, convert it with Number() before doing arithmetic.
console.log("5" + 3);
console.log(Number("5") + 3);
console.log("5" * 3);
console.log(Number("abc"));
console.log(typeof 42, typeof "42", typeof true, typeof undefined);53
8
15
NaN
number string boolean undefinedThe multiplication line shows that * converts its operands to numbers, so "5" * 3 is 15, while + prefers text. NaN means "not a number" and is the result of an invalid conversion. The seven primitive types and type coercion cover what each type holds and how the conversions work, and you can return to them after stage three.
Project. Write a script that stores a price, a quantity and a tax rate in variables, calculates the total and prints a three-line receipt. Then change the quantity and run it again. You are ready for stage two when you can explain why a variable declared with const can be printed but not reassigned, and what each line of the receipt prints before you run it.
Stage 2: decisions and loops
A program that does the same thing every time is a calculator. Decisions and loops are what make it a program. A decision chooses between paths with if, else if and else, based on a condition that is true or false. A loop repeats a block while a condition holds, with for when you know how many times and while when you do not.
Conditions use comparison operators. Use === and !== to test equality, and <, >, <= and >= for order. === compares without converting types, so 5 === "5" is false, and it is the one to use. The older == converts first and has surprising results, covered later in loose equality.
const output = [];
for (let n = 1; n <= 15; n += 1) {
if (n % 15 === 0) {
output.push("FizzBuzz");
} else if (n % 3 === 0) {
output.push("Fizz");
} else if (n % 5 === 0) {
output.push("Buzz");
} else {
output.push(n);
}
}
console.log(output.join(" "));1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzzThis is the classic FizzBuzz puzzle, and it teaches three things at once. The loop header has three parts: a starting value, a condition that keeps it going and a step. The order of the if branches matters, because a number divisible by both 3 and 5 would also match the first test it meets, so the most specific case must come first. And output.push(n) adds an item to the end of an array, which is stage four's subject arriving early.
Know what counts as true. Conditions accept any value and convert it: false, 0, "", null, undefined and NaN are falsy, and everything else, including "0" and an empty array, is truthy. The complete list of truthy and falsy values is short enough to learn.
let guess = 1;
let steps = 0;
const secret = 37;
while (guess !== secret) {
guess = Math.min(guess * 2, secret);
steps += 1;
}
console.log(`reached ${guess} in ${steps} steps`);
for (const letter of "abc") {
console.log(letter);
}reached 37 in 6 steps
a
b
cThe while loop doubles the guess until it hits the secret, capping at the secret, which takes six doublings from 1: 2, 4, 8, 16, 32, then capped at 37. A while loop with a condition that never becomes false runs forever, and pressing Ctrl+C stops it, so write the exit condition before the body. for...of walks the items of a string, an array and anything else iterable, and it is the loop you will use most for collections.
Project. Write a program that prints the multiplication table for 7 from 1 to 10, then a second that finds all numbers from 1 to 50 that are divisible by 4 but not by 6. You are ready for stage three when you can write a loop with an exit condition on the first attempt and say why <= or < was the right choice for it.
Stage 3: functions
A function packages a calculation under a name so that you can use it many times and read the result as a sentence. It takes parameters, does work and returns a value. A function that depends only on its parameters and returns a result without changing anything else is called pure, and pure functions are the easiest code to test and to trust.
function countWords(text) {
const counts = {};
for (const word of text.toLowerCase().match(/[a-z']+/g) ?? []) {
counts[word] = (counts[word] ?? 0) + 1;
}
return counts;
}
const counts = countWords("The cat and the hat. The END!");
console.log(counts);
const topWords = (counts, limit = 2) =>
Object.entries(counts)
.toSorted((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.slice(0, limit);
console.log(topWords(counts));{ the: 3, cat: 1, and: 1, hat: 1, end: 1 }
[ [ 'the', 3 ], [ 'and', 1 ] ]countWords takes text and returns an object of counts. The regular expression /[a-z']+/g finds runs of letters, and match returns null when there is nothing, which the ?? [] turns into an empty list so the loop does nothing. counts[word] ?? 0 supplies a starting value of zero for a word seen for the first time. The second function is an arrow function, the short form, with a default parameter: limit = 2 is used when the caller passes nothing. The sort compares by count first, and when counts are equal, by the word, so the output is the same on every run.
Three habits are worth building now. Give a function one job and a name that says it, so countWords and topWords are two functions and not one. Return values instead of printing inside them, so the caller decides what to do with the result and a test can check it. Do not change the arguments you receive, because an object passed in is the caller's object, and changing it surprises them, a point stage four makes concrete.
Functions are values too: you can store them in variables, pass them to other functions and return them from functions. That idea is what makes map, filter and callbacks work, and it leads to closures in stage six.
Project. Write isPalindrome(text) that ignores case and anything that is not a letter, then longestWord(text). Call each with three inputs, including an empty string. You are ready for stage four when your functions take input and return output without printing, and you can say what a function returns when it has no return statement. The answer is undefined.
Stage 4: arrays and objects
Real data is lists of records. An array is an ordered list, and an object is a record of named values. Together they model almost everything: a list of products, a user with an address, the lines of an order. Arrays have a rich set of methods, and the three that carry most work are map, which transforms each item, filter, which keeps some, and reduce, which folds a list into one value.
const products = [
{ name: "pen", price: 2.5, stock: 10 },
{ name: "pad", price: 8.99, stock: 0 },
{ name: "ink", price: 12, stock: 4 },
];
const inStock = products.filter((product) => product.stock > 0);
const names = inStock.map((product) => product.name);
const value = inStock.reduce((sum, product) => sum + product.price * product.stock, 0);
console.log(names, value);
const cheapest = products.toSorted((a, b) => a.price - b.price)[0];
console.log(cheapest.name, products[0].name);
const pad = products.find((product) => product.name === "pad");
console.log(pad?.price, products.find((product) => product.name === "cap")?.price);[ 'pen', 'ink' ] 73
pen pen
8.99 undefinedfilter keeps the products with stock, map takes their names and reduce adds up price times stock, starting from the 0 passed as its second argument. None of the three changes the original array: toSorted returns a sorted copy, which is why products[0] is still the pen. find returns the first match or undefined, and the ?. after it, optional chaining, reads price only when something was found. Reading a property of undefined without it throws an error, the first one in stage five.
Objects need one more idea: values that are objects or arrays are shared, not copied. When you assign an object to another variable or pass it to a function, both names refer to the same object, and a change through one is visible through the other.
const original = { name: "pen", tags: ["office"] };
const alias = original;
alias.name = "pencil";
const shallowCopy = { ...original };
shallowCopy.tags.push("school");
const deepCopy = structuredClone(original);
deepCopy.tags.push("art");
console.log(original);
console.log(deepCopy.tags);{ name: 'pencil', tags: [ 'office', 'school' ] }
[ 'office', 'school', 'art' ]alias is the same object, so renaming through it renamed original. The spread copy { ...original } made a new top-level object, but tags inside it is still the same array, so the push showed through. structuredClone copies every level, so deepCopy can change without touching the original. Most "my data changed and I do not know why" bugs are this one, and primitives versus objects and shallow versus deep copy explain it in full.
Learn the array methods by use, not by memorizing a table. The posts on [filter()](/library/javascript-array-filter), [find()](/library/javascript-array-find), [flatMap()](/library/javascript-array-flatmap) and [includes()](/library/javascript-array-includes) each name the trap that goes with the method.
Project. Model a small library: an array of books with a title, an author, a year and a flag for borrowed. Write functions that list the available titles, group the books by author and find the oldest. You are ready for stage five when you can transform a list without writing a loop with an index, and can predict whether a change will show through a second name.
Stage 5: errors and debugging
Everyone writes code that fails. The skill that separates a beginner from a productive developer is reading the failure. JavaScript reports problems in two ways: a syntax error before the program runs, when the code cannot be parsed, and a runtime error while it runs, as a thrown Error object with a name, a message and a stack trace that lists the calls in progress.
const user = undefined;
function attempt(label, action) {
try {
action();
} catch (error) {
console.log(`${label}: ${error.name}: ${error.message}`);
}
}
attempt("property of undefined", () => user.name);
attempt("unknown name", () => missingFunction());
attempt("not a function", () => ({}).load());
attempt("reassign const", () => {
const limit = 5;
limit = 6;
});
attempt("bad array length", () => new Array(-1));property of undefined: TypeError: Cannot read properties of undefined (reading 'name')
unknown name: ReferenceError: missingFunction is not defined
not a function: TypeError: (intermediate value).load is not a function
reassign const: TypeError: Assignment to constant variable.
bad array length: RangeError: Invalid array lengthEach error type says what went wrong. A TypeError means a value was not the type the operation needed, usually undefined where an object was expected. A ReferenceError means a name does not exist in scope, which is usually a typo or a missing import. A RangeError means a number was out of the allowed range. A SyntaxError means the code is not valid JavaScript, and it names the line.
Reading a stack trace goes from the top: the first line names the error, and the first frame below it is where it was thrown. Your own file is the frame to look at, not the lines inside Node.js internals. Then work backward through the frames to see how the bad value got there. For Cannot read properties of undefined (reading 'name'), the question is always the same: which variable was undefined, and why did it have no value?
Three tools find the answer. console.log of the suspect value, one line above the failing one, is the first and works every time. The second is the debugger: run node --inspect-brk file.mjs, open chrome://inspect in Chrome and step through the code line by line with the values visible. The third is the habit of making a smaller reproduction. Delete everything that is not needed to trigger the error, and the cause usually becomes visible before the last line is gone.
Handle errors you can recover from and let the rest stop the program. A try and catch around code that you cannot do anything about hides the failure. Error handling with try, catch and finally covers where each belongs, and custom error classes shows how to give your own errors a name callers can test.
Project. Take three programs from stages one to four and break each in a different way: a typo in a name, a missing property and a wrong argument. Write down the exact error message each produces and what it means. You are ready for stage six when you can find the line that caused an error from its message and stack without searching for it first.
Stage 6: scope, closures and this
Scope decides where a name can be used. A name declared with let or const exists in the block where it is written and in the blocks inside it, and not outside. When code uses a name, the engine looks in the current block, then the one around it, and so on outward until it finds the name or fails with a ReferenceError. This is lexical scope: it depends on where code is written, not where it is called.
A closure follows from that rule. A function remembers the scope in which it was created, even after that scope has finished.
function createCounter(start = 0) {
let count = start;
return {
next() {
count += 1;
return count;
},
peek: () => count,
};
}
const first = createCounter();
const second = createCounter(100);
first.next();
first.next();
console.log(first.peek(), second.peek());
const callbacks = [];
for (var i = 0; i < 3; i += 1) callbacks.push(() => i);
console.log(callbacks.map((callback) => callback()));
const fixed = [];
for (let j = 0; j < 3; j += 1) fixed.push(() => j);
console.log(fixed.map((callback) => callback()));2 100
[ 3, 3, 3 ]
[ 0, 1, 2 ]Each call to createCounter creates a new count that only the two returned functions can reach, so first and second keep separate counts and nothing outside can change them. The loop example is the best-known closure puzzle. With var, there is one i for the whole function, so every callback sees its final value, 3. With let, each iteration gets a fresh j, so each callback keeps its own. This is the main reason to avoid var.
The this keyword is the other idea in this stage. In a method, this is the object the method was called on, and it is decided at call time, not where the function was written. Arrow functions are the exception: they take this from the code around them. Passing a method as a callback detaches it from its object, and this is lost.
const timer = {
label: "build",
start() {
return [1, 2].map((n) => `${this.label}-${n}`);
},
};
console.log(timer.start());
const detached = timer.start;
try {
detached();
} catch (error) {
console.log(error.name);
}[ 'build-1', 'build-2' ]
TypeErrorThe arrow function inside start reads this from start, which is timer. Calling detached() has no object in front of it, so this is undefined in a module and this.label throws. When you hit this bug, the fix is an arrow function, .bind(timer), or not passing the method around. Scope, hoisting and closures and [the this keyword](/library/keyword-works-javascript) cover both ideas in depth.
Project. Write a function once(fn) that returns a function that calls fn the first time and returns the same result for every call after that. Then write a debounce-style function that remembers the last call. You are ready for stage seven when you can say, for any variable in your code, where it is visible and which function holds a reference to it.
Stage 7: modern syntax and modules
By now you can write programs that work. This stage is about writing them the way current JavaScript is written, and about splitting them across files. The syntax in question is small: destructuring to unpack values, spread and rest to expand and collect them, optional chaining and the nullish operator for missing data.
const order = { id: 7, customer: { name: "Mei", address: null }, items: ["pen", "ink"] };
const {
id,
customer: { name },
items: [firstItem, ...otherItems],
} = order;
console.log(id, name, firstItem, otherItems);
console.log(order.customer.address?.city ?? "no address on file");
const defaults = { retries: 3, verbose: false };
const options = { ...defaults, verbose: true };
console.log(options);
function describe({ method = "GET", path }, ...flags) {
return `${method} ${path} [${flags.join(",")}]`;
}
console.log(describe({ path: "/orders" }, "json"));7 Mei pen [ 'ink' ]
no address on file
{ retries: 3, verbose: true }
GET /orders [json]The first statement pulls id, the nested name and the first item of the array out of the order in one line, and collects the rest of the items into a new array. order.customer.address?.city stops at the null address and gives undefined, and ?? replaces that with a message. Spread builds a new object from defaults and then overrides one field, which is the pattern for options with defaults. Destructuring, spread versus rest, optional chaining and [?? versus ||](/library/nullish-coalescing-vs-logical-compared-operator) each have a post.
Modules split a program into files. A module exports what other files may use and imports what it needs. Everything not exported stays private to its file.
// pricing.mjs
const TAX_RATE = 0.2;
export function withTax(net) {
return Math.round(net * (1 + TAX_RATE));
}
export const currency = "USD";// main.mjs
import { withTax, currency } from "./pricing.mjs";
console.log(withTax(100), currency);120 USDRun node main.mjs with both files in one folder. TAX_RATE is not exported, so no other file can read it. A relative import in Node.js includes the file extension. A file may also have one default export, imported without braces, though named exports are easier to search for and rename. Imports are live bindings, which ES modules explained describes, and a module runs once no matter how many files import it.
Project. Take the library project from stage four and split it into three files: the data, the functions that work on it and a main.mjs that prints a report. You are ready for stage eight when a new function can be added in one file and used in another without editing the data file, and you can say what export does and what stays hidden without it.
Stage 8: asynchronous code
Some work takes time: reading a file, calling a server, waiting for a timer. A program that stops and waits for each one would be useless, so JavaScript starts the work and moves on, and runs your code later when the result is ready. A promise is the object that stands for such a result. It is pending, then fulfilled with a value or rejected with an error.
async and await let you write code that waits as if it ran in a straight line. An async function always returns a promise, and await pauses that function until the promise settles, producing its value or throwing its error. The rest of the program keeps running while the function waits, which is why you can use try and catch around an await.
async function retry(task, { attempts = 3, delayMs = 10 } = {}) {
let lastError;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
return await task(attempt);
} catch (error) {
lastError = error;
console.log(`attempt ${attempt} failed: ${error.message}`);
await new Promise((resolve) => setTimeout(resolve, delayMs * attempt));
}
}
throw new Error("all attempts failed", { cause: lastError });
}
const flaky = async (attempt) => {
if (attempt < 3) throw new Error("timeout");
return `ok on attempt ${attempt}`;
};
console.log(await retry(flaky));
try {
await retry(async () => {
throw new Error("server down");
}, { attempts: 2 });
} catch (error) {
console.log(error.message, "<-", error.cause.message);
}attempt 1 failed: timeout
attempt 2 failed: timeout
ok on attempt 3
attempt 1 failed: server down
attempt 2 failed: server down
all attempts failed <- server downretry runs a task, and if it throws, waits a little longer each time and tries again, up to a limit. The first call succeeds on its third attempt. The second never does, so it throws a new error that keeps the last failure as its cause. The await new Promise(...) line is the standard way to wait for a timer. Top-level await, used for the two calls at the bottom, works in a module and saves a wrapper function.
The common mistakes at this stage are forgetting await, which leaves you with a pending promise where you expected a value, and awaiting in a loop when the work could run together. To run independent tasks at the same time, start them all and await them together.
const wait = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const started = Date.now();
const results = await Promise.all([wait(30, "a"), wait(30, "b"), wait(30, "c")]);
const elapsed = Date.now() - started;
console.log(results);
console.log(elapsed < 80);
const outcomes = await Promise.allSettled([wait(5, "fine"), Promise.reject(new Error("broken"))]);
console.log(outcomes.map((outcome) => outcome.status));[ 'a', 'b', 'c' ]
true
[ 'fulfilled', 'rejected' ]Three waits of 30 milliseconds ran together and finished in about 30, not 90, which the comparison confirms without printing a figure that would differ on every machine. Promise.all rejects as soon as one promise does. Promise.allSettled waits for all of them and reports each outcome. To understand why await behaves as it does, and why a timer of zero still runs after your synchronous code, read how JavaScript actually runs, which covers the call stack, the event loop and microtasks.
Project. Write a function fetchAll(urls) that, using a fake fetchOne you write with a timer, loads every item concurrently, retries a failure once and returns the successes and the failures separately. You are ready for stage nine when you can say why a function that forgot an await returns a promise, and when a loop should use await in the body and when it should not.
Stage 9: files, arguments and the platform
JavaScript the language has no files, no network and no screen. Those belong to the platform it runs in. In a browser the platform is the DOM, fetch and localStorage. In Node.js it is modules such as node:fs, node:path, node:http and the process object. Knowing where the language ends and the platform begins keeps you from searching for a language feature that is really a runtime API. What JavaScript and ECMAScript are draws the line.
A command-line tool is the best next project, because it uses everything so far and needs no browser. Create a file sales.json:
[
{ "region": "north", "amount": 120 },
{ "region": "south", "amount": 80 },
{ "region": "north", "amount": 50 }
]Then write a script that takes the file name as an argument and prints the total for each region.
// report.mjs
import { readFile } from "node:fs/promises";
const [, , file] = process.argv;
if (!file) {
console.error("usage: node report.mjs <file.json>");
process.exit(1);
}
const sales = JSON.parse(await readFile(file, "utf8"));
const totals = new Map();
for (const { region, amount } of sales) {
totals.set(region, (totals.get(region) ?? 0) + amount);
}
for (const [region, total] of totals) {
console.log(region.padEnd(6), total);
}north 170
south 80Running node report.mjs sales.json prints the two lines above. process.argv is the list of command-line arguments: the first is the path to Node.js, the second is the script, and the third onward are yours, which the destructuring [, , file] skips to. readFile from node:fs/promises returns a promise for the file's contents, JSON.parse turns the text into data and a Map accumulates a total for each region. Running it without an argument prints the usage line to standard error and exits with a non-zero code, which is how a program reports failure to the shell.
Handle the failures this tool will meet: a file that does not exist, and a file that is not valid JSON. Each throws, and each should produce a message the user can act on, not a stack trace.
import { readFile } from "node:fs/promises";
async function loadJson(path) {
let text;
try {
text = await readFile(path, "utf8");
} catch (error) {
if (error.code === "ENOENT") throw new Error(`file not found: ${path}`, { cause: error });
throw error;
}
try {
return JSON.parse(text);
} catch (error) {
throw new Error(`not valid JSON: ${path}`, { cause: error });
}
}
try {
await loadJson("missing.json");
} catch (error) {
console.log(error.message);
console.log(error.cause.code);
}file not found: missing.json
ENOENTThe function turns a low-level error code, ENOENT, into a message for a person, and keeps the original in cause for logs. Reading the Node.js documentation for node:fs, node:path and process is a good use of an hour at this point, because the platform is a large part of what you will do with the language. The same applies to the browser: if your goal is the front end, now is the time to learn the DOM, events and fetch, with the language already solid.
Project. Extend the report tool to accept a second argument, a minimum amount, and to print regions sorted by total from highest to lowest, with a friendly error for each failure above. You are ready for stage ten when you can read a platform API's documentation page, find the function you need, and call it correctly from its signature.
Stage 10: tests
A test is code that checks that other code does what you expect, and runs in a second instead of by hand. Tests let you change code without fear, because a change that breaks something shows up at once. Node.js has a test runner built in, so you need no package.
The strongest habit is to write the test first. State what the function should do as examples, watch them fail, then write the function until they pass. Writing the examples first forces you to decide what the function should do with the awkward inputs, such as an empty string, before the code has opinions of its own.
// slugify.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { slugify } from "./slugify.mjs";
test("lower-cases and joins words with hyphens", () => {
assert.equal(slugify("Hello, World!"), "hello-world");
});
test("collapses spaces and trims the ends", () => {
assert.equal(slugify(" Many spaces "), "many-spaces");
});
test("returns an empty string for text with no letters or digits", () => {
assert.equal(slugify("!!!"), "");
});// slugify.mjs
export function slugify(text) {
return text
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}✔ lower-cases and joins words with hyphens (0.8ms)
✔ collapses spaces and trims the ends (0.1ms)
✔ returns an empty string for text with no letters or digits (0.1ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 38.5Run it with node --test, which finds files that end in .test.mjs. The first replace turns every run of characters that are not letters or digits into one hyphen, and the second removes hyphens at the start and the end. The durations differ on every run. If a test fails, the runner prints the expected and actual values side by side, with the line of the assertion.
A good test checks one behavior and names it in plain words, so that a failure reads as a sentence. Test the edges, not only the middle: empty input, a single item, the largest and smallest values, and what should happen on bad input. Do not test the language itself, and do not copy the function's logic into the test, because a test that repeats the code cannot find its mistakes.
For code with waiting or a clock in it, make time controllable. The runner can replace timers and Date for a test, and a function that takes the current time as an argument needs no fake at all. Testing code that depends on time in the guide to dates shows both.
Project. Write tests first for isPalindrome, countWords and your retry function from stage eight, including the failing cases. Then break each function deliberately and confirm that a test notices. You are ready for stage eleven when you reach for a test before reaching for console.log, and can say what a failing test is telling you.
Stage 11: tools
A project is a folder with a package.json. That file names the project, lists its dependencies and defines scripts. Create one with npm init -y, then set "type": "module" so that .js files are treated as ES modules, and add scripts for the commands you run often.
{
"name": "shop-reports",
"version": "1.0.0",
"private": true,
"type": "module",
"engines": { "node": ">=24" },
"scripts": {
"start": "node src/main.js",
"dev": "node --watch src/main.js",
"test": "node --test",
"lint": "eslint ."
}
}npm start runs the program, npm run dev restarts it when a file changes, npm test runs the tests and npm run lint checks the code. Dependencies are added with npm install name, which records them in package.json and pins exact versions in package-lock.json. Commit both files to version control, and every machine that installs the project gets the same code.
Three tools do most of the work in a project. Git records every change and lets you undo one, so learn git init, git add, git commit, git diff and git log before the first project you care about. ESLint reads your code without running it and reports mistakes the language allows, such as an unused variable or a comparison that is always true. Prettier formats code one way, so no review comment is ever about spacing.
/home/dev/shop-reports/src/main.js
3:7 error 'unused' is assigned a value but never used no-unused-vars
9:3 error 'total' is not defined no-undef
✖ 2 problems (2 errors, 0 warnings)The paths and line numbers in a report depend on your project. Treat a lint error as a question, not a nuisance: each rule exists because the pattern it catches has caused a bug somewhere. Disable a rule for one line only with a comment that says why.
Dependencies deserve caution. Every package you install is code you did not write, running with your permissions, along with the packages it depends on. Install what you need, prefer well-maintained packages with a small footprint, read what they do before you trust them with secrets and run npm audit to see known problems. For many tasks, Node.js already has what you need: fetch, a test runner, --env-file, --watch, crypto.randomUUID() and structuredClone are all built in.
TypeScript is the tool people ask about most. It adds types that are checked before the code runs and erased afterward, so it catches a wrong argument or a missing property at your desk rather than in production. Learn it after you are comfortable with JavaScript, not before, because it describes the language and cannot replace understanding it. Node.js 24 can run a .ts file directly when it uses only erasable syntax, so trying it costs little.
Project. Put your report tool and its tests in a folder with a package.json, scripts, ESLint and Prettier, and a Git repository with at least three commits. You are ready for stage twelve when a new machine can run npm install, npm test and npm start with no instructions beyond that.
Stage 12: production habits
Code that runs for someone else, unattended, needs more than code that works on your laptop. This last stage is a set of habits and one project, a small HTTP server, that put the earlier stages together and add what a service needs.
Configuration comes from the environment. Never write a password, a key or a port into the source. Read them from environment variables, validate them at start-up and fail with a clear message when they are wrong, so the program does not run for an hour before it finds out.
function readConfig(env) {
const port = Number(env.PORT ?? 3000);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new RangeError(`PORT must be 1 to 65535, got ${env.PORT}`);
}
return { port, mode: env.NODE_ENV === "production" ? "production" : "development" };
}
console.log(readConfig({ PORT: "8080", NODE_ENV: "production" }));
try {
readConfig({ PORT: "abc" });
} catch (error) {
console.log(error.name + ": " + error.message);
}{ port: 8080, mode: 'production' }
RangeError: PORT must be 1 to 65535, got abcPassing process.env in as an argument keeps the function easy to test, and node --env-file=.env loads a local file of variables without a package. Keep that file out of version control.
Treat all input as untrusted. Anything that comes from a user, a request, a file or another service can be wrong or hostile. Validate its shape and range, and escape it for the place it is going. Text put into HTML must be escaped, a value put into a database query must go through a parameter and not a string join, and a file path built from input must be checked against the folder it is allowed to reach. Never run text as code, which rules out eval and new Function on anything a user supplied.
const escapeHtml = (text) =>
text
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
console.log(escapeHtml('<img src=x onerror="alert(1)">'));<img src=x onerror="alert(1)">The ampersand must be replaced first, or the entities written by the later replacements would be escaped a second time. A template library or a framework normally does this for you, and knowing what it is doing is what lets you notice the one place it was turned off.
Log what happened and fail loudly. A service has no screen, so its logs are how you find out what it did. Write one line per event with enough detail to act on, never log a password or a token, and let an unexpected error end the request with a clear status instead of hanging or hiding it. Handle unhandledRejection, because an unnoticed failed promise is the usual way a service stops working without a message.
Keep the event loop free. Node.js runs your code on one thread, so a long calculation or a synchronous file read inside a request handler blocks every other request until it ends. Use the asynchronous APIs, split long work into chunks or move it to a worker thread.
The project is a small server that answers a health check, which every deployment platform asks for. It starts, answers two requests from the same script and shuts down, so you can see the whole life cycle in one run.
import { createServer } from "node:http";
const server = createServer((request, response) => {
const url = new URL(request.url, "http://127.0.0.1");
if (request.method === "GET" && url.pathname === "/health") {
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify({ ok: true }));
return;
}
response.writeHead(404, { "content-type": "application/json" });
response.end(JSON.stringify({ error: "not found" }));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const { port } = server.address();
const health = await fetch(`http://127.0.0.1:${port}/health`);
console.log(health.status, await health.json());
const missing = await fetch(`http://127.0.0.1:${port}/nope`);
console.log(missing.status, await missing.json());
server.close();200 { ok: true }
404 { error: 'not found' }Listening on port 0 asks the operating system for any free port, which is how the script avoids clashing with another program, and server.address() reports the one it got. A real service reads its port from the configuration above. The handler checks the method and the path, answers JSON with the right status and sets the content type. In a real project, you would add a router or a framework such as Express or Fastify, a validation layer for request bodies, structured logging and a graceful shutdown that stops accepting requests and lets the current ones finish. Those are additions to this core, not replacements for it.
Project. Turn the report tool into a service: an endpoint that accepts a list of sales as JSON, validates it, returns the totals by region and rejects bad input with a 400 status and a message. Write tests that start the server on a free port and call it with fetch. You are finished with the roadmap when a stranger could clone the repository, read the README, run the tests and start the service, and you could explain every line of it.
What to skip on the way
Some of the usual advice slows a beginner down, and a few things should wait.
Frameworks before the language. React, Vue, Svelte and Angular are written in JavaScript and assume you can read it. A learner who starts with one cannot tell a framework rule from a language rule, and meets a bug that mixes the two with no way in. Finish stage eight first. When you do start one, you will read its documentation as a user of the language and not as a tourist.
Algorithms and data structures as a course. They matter, and they are a separate subject that you can study in any language. For this roadmap the arrays, objects, maps and sets are enough, and the point is to model real data well.
Every array method. There are dozens. Learn map, filter, find, reduce, some, every, includes and sort first, and look up the rest when a task needs one.
Old syntax for its own sake. You will meet var, callbacks nested four deep, function constructors with prototype assignments and require. Learn to read them, because they are in the code you will inherit, and do not write them in new code.
Memorizing the specification. The language is defined in a long document, and nobody who works in it knows it by heart. Learn to read the reference, such as MDN or the Node.js documentation, and to find the answer in it. That skill lasts longer than any fact.
Getting unstuck
Everyone is stuck often, and the method for getting out matters more than the intelligence of the person stuck. Work through these in order before asking anyone.
Say the problem out loud, or write it down. "I expect X, I get Y, and I think the cause is in Z." Many problems dissolve at this step.
Read the error message to the end. The message and the first frame in your own file usually name the cause.
Shrink the problem. Delete code until the smallest program that still shows the problem is left. Then the cause is in what remains.
Print the values.
console.logthe inputs of the line that fails, and compare them with what you assumed.Look up the function. The reference page states what it returns, what it does with bad input and what changed between versions.
Search with the exact error text in quotation marks, add the runtime name, and prefer official documentation and the project's own issue tracker over a copied answer you cannot verify.
Ask with a reproduction. A question that includes a short program, its output and the expected output gets answered. A question that says "it does not work" does not.
When you read an answer, run it and change it before you trust it. An answer that you copied without understanding is a bug you have not met yet.
Where this roadmap stops
This roadmap teaches the language, the Node.js runtime and the habits of a working programmer, and it stops at a small service. It does not cover the browser in depth, so if you want to build interfaces, the next subjects are the DOM, events, the browser's storage and network APIs, and CSS. It does not cover databases, so for persistent data you would learn SQL and a client library. It does not cover deployment: containers, hosting and monitoring are a separate set of skills. And it does not cover the deeper parts of the language itself, such as prototypes, iterators, proxies, typed arrays and the memory model, which are the subject of the posts linked throughout this guide, beginning with how JavaScript actually runs, the types and coercion guide and the prototype guide.
The roadmap is a path, and a path is not the only valid one. If you already program in another language, you can move through stages one to four in an afternoon and spend your time on stages six to eight, where JavaScript differs most. If your goal is a browser interface, do stages one to eight and then switch to the DOM, returning to stages nine to twelve when you need a server. What does not change is the method: write the code, predict the output, break it on purpose and read the error. The rest is repetition.


