JavaScript from scratch
JS Saga with Byte the cat
Byte is a cat and a senior developer. He tells theory as tales, builds programs with you in workshops, sends you into labs and sets bosses on you. Learning will be funny — and for real.
// in exactly that order. probably.
Tale
Theory from Byte. Examples run right in the text.
Why?
One "why" explored to the bottom. Ends with "myth or fact".
Workshop
Build a program step by step; tests check every step.
Investigation
Code from a "real app" with a bug. Find it and fix it.
Lab
A real challenge with no step-by-step help.
Boss
The chapter finale: a quiz with three lives.
Part 1 · Basics
Chapter 1
How to keep values in variables, how let differs from const, what types of values exist, and why "2" + 3 is "23".
- Tale
Byte clears out the attic
Variables, let and const, types of values and typeof.
- Why?
Why is typeof null "object"?
A bug from 1995 that can't be fixed, and the difference between null and undefined.
- Workshop
Labels for the attic
Gluing strings, typeof and both together — four small functions for listing boxes.
- Investigation
The case of the 32 fish cakes
A customer added 2 fish cakes to the cart, and it suddenly held 32. Find the bug.
- Lab
Celsius to Fahrenheit
No steps and no hints from Byte — just you and the tests.
- Boss
The Null Ghost
It haunts the attic and pretends to be an object. Three lives, seven questions.
Chapter 2
How to pack actions into a function, hand it data and get a result back with return. Arrow functions and callbacks.
- Tale
How Byte stopped repeating himself
Functions, parameters and return, default values, arrow functions and callbacks.
- Why?
Why isn't console.log the same as return?
Why a function "printed everything" or "computed everything" and still returns undefined: three reasons.
- Workshop
The Purrlatte café till
Build a till program out of small functions — step by step.
- Investigation
The case of the empty receipt
The cart says "Total: undefined". Find the bug.
- Lab
Sum of two numbers
No steps, no hints from Byte — just you and the tests.
- Boss
The Great Undefined
It feeds on functions without return. Three lives, eight questions.
Chapter 3
Comparisons, if / else, logical operators, % and switch — and why === beats ==.
Reward: Rex- Tale
Byte becomes a bouncer
How a program makes decisions: comparisons, if, else if, && and ||, the remainder % and switch.
- Why?
Why is === better than ==?
Why double equals can "coerce types", where strict comparison hides without ===, and how % trips on negative numbers.
- Workshop
The robot bouncer
Program face control: age, a blacklist, a greeting.
- Investigation
The case of the missing discount
Nobody at all gets the student and senior discount. Find the bug.
- Lab
Even number
One remainder and one comparison. Can you do it without Byte?
- Boss
Two-Faced ==
It's sure that "1" and 1 are the same thing. Three lives, eight questions.
Chapter 4
Arithmetic and remainders, rounding, turning strings into numbers, NaN and Infinity — and why money is counted in cents.
- Tale
Byte becomes an accountant
Arithmetic, %, rounding, toFixed, Number and parseInt, NaN, Infinity and random numbers.
- Why?
Why is 0.1 + 0.2 !== 0.3?
Binary fractions, the IEEE 754 standard — and how to live with them: comparing with a tolerance and keeping money in integers.
- Workshop
The till at Purr & Pastry
Converting to cents, reading a price from a form, boxes, splitting a bill and a neat price tag — five steps of a till.
- Investigation
The case of the $349.90150.00 receipt
A customer got a receipt for three hundred forty-nine thousand and change. Find the bug.
- Lab
Volume slider
Keep a number inside its limits — try it without a single if, using Math.min and Math.max.
- Boss
The Auditor
He checks every cent. Balance the books without a single mistake.
Chapter 5
Lists of values, zero-based indexes, for...of, while, break/continue, searching with includes/indexOf, and the accumulator pattern.
- Tale
Byte's sock empire
Arrays, length, indexes, push, for and while loops, break/continue, includes and indexOf.
- Why?
Why do indexes start at zero?
Where the zero index came from, why it's handier than it seems, and why “not found” is -1.
- Workshop
The sock warehouse
Count, find, pack and weigh the loot — nine steps with loops, while, break/continue and searching.
- Investigation
The case of NaN socks
The warehouse program says there are "NaN" socks. Find the bug.
- Lab
Largest number
Find the maximum in an array — with the same trick as in the warehouse.
- Boss
The Infinite Loop
It spins and never stops. Find the exit condition.
Part 2 · Text and data
Chapter 6
Text in a program: length, letters by index, string methods, template strings, and why a string can't be "fixed in place".
- Tale
Byte starts a newspaper
Strings, length, indexes, toUpperCase, slice, includes and template strings.
- Why?
Why can't you fix a string?
Why text[0] = "C" does nothing, and string methods always return a new string.
- Workshop
The Gazette newsroom
Headlines, teasers, censorship and bylines — five steps with strings.
- Investigation
The case of the double letter
In the greeting, every user's first letter is doubled. Find the bug.
- Lab
Trim a teaser
Cut text to a given length with an ellipsis — like in news cards.
- Boss
The Typo
It hides in every headline. Catch it.
Chapter 7
Searching by pattern instead of exact text: test, match, replace, character classes, quantifiers, anchors and groups — and when a regex is the wrong tool.
Reward: Detective hat- Tale
The detective searches by description
Regular expressions, test, match, replace, the g and i flags, \d, \w, \s, quantifiers, ^ and $, groups.
- Why?
Why do regexes look like line noise?
Where this mini-language came from, why it's so terse, how to read it piece by piece, and when you don't need it.
- Workshop
The detective's case files
Cleaning statements and phone numbers, finding hashtags, checking nicknames and rearranging dates — five steps with regexes.
- Investigation
The case of 119:300 o'clock
The booking form accepts times that don't exist. Find the bug in the check.
- Lab
A page address from a title
Turn a title into a slug like hello-world. The regex \s+ comes in very handy here.
- Boss
Professor Asterisk
He hides clues in patterns. Read every one.
Chapter 8
Related data under one name: properties, the dot and square brackets, keys, copies and references.
Reward: Mittens- Tale
A passport for a cat
Objects, properties, the dot and brackets, in, Object.keys and ?..
- Why?
Why did the "copy" change?
Why const b = a doesn't copy an object, and how to make a real copy.
- Workshop
The passport office
Issue, read and reissue cat passports — five steps with objects.
- Investigation
The case of the spoiled passport
Registering a kitten rewrote its mother's passport. Find the bug.
- Lab
Default settings
Merge default settings with the user's choices.
- Boss
The Doppelgänger
It looks like a copy, but it's the same object.
Chapter 9
How to unpack an object or array into variables in one line, how a function accepts any number of arguments, and what the three dots ... mean in different places.
Reward: Oscar- Tale
Unpacking parcels
Object and array destructuring, default parameters, rest and spread.
- Why?
Why is `...` both spread and rest?
One symbol, two opposite operations: how JavaScript knows whether to gather or scatter.
- Workshop
The sorting room
Labels, rates, weighing, the queue and redirects — five steps with destructuring, rest and spread.
- Investigation
The case of the texts for everyone
One cat turned on text notifications — and everyone got them. Find the bug.
- Lab
Invert an object
Swap keys and values — destructuring pairs comes in handy.
- Boss
The Repacker
He opens parcels and shuffles their contents. Predict what ends up in each one.
Chapter 10
Processing lists without hand-written loops: transform each item, keep the ones you need, fold everything into one result.
- Tale
The conveyor at the fish factory
map, filter, reduce, find, some, method chains, plus forEach, findIndex, flat/flatMap and the sneaky sort.
- Why?
Why map and not a loop?
Why modern code processes lists with methods, which methods do change the array, and when a loop is better.
- Workshop
A shift on the conveyor
Select, label, weigh, unload and sort the catch — nine steps with array methods.
- Investigation
The case of the blank price tags
The shop's price tags show undefined. Find the bug.
- Lab
Names of adults
Select and transform — with a filter and map chain.
- Boss
The jammed conveyor
The belt has stopped. Find out which station is to blame.
Chapter 11
Lists without duplicates and dictionaries with keys of any type: when plain arrays and objects stop being enough, and why.
Reward: Tiger- Tale
Byte's cat show
Set: unique values. Map: key → value pairs with keys of any type.
- Why?
Why not a plain object?
What makes an object a poor dictionary, and why Map and Set were added to the language.
- Workshop
The front desk
Guests, breeds, gatecrashers, the vote and hall seats — five steps with Map and Set.
- Investigation
The case of the look-alike crowd
The unique-visitor counter treats every visit as a new guest. Find the bug.
- Lab
Has duplicates
Has this guest been here before? A Set answers instantly.
- Boss
The Doppelganger
He sneaks into the show twice in different disguises. Unmask him.
Part 3 · Functions and objects in depth
Chapter 12
Who sees which variables, why a function remembers the variables it was born among, and how private memory is built on that.
- Tale
Who reads the diary
Scope, nested functions and closures.
- Why?
Why didn't the variable disappear?
Why a local variable lives on after its function has finished.
- Workshop
The secret diary
An entry counter, greetings, a password lock and a read limit — four steps with closures.
- Investigation
The case of the silent buttons
Every button in the diary's menu shows undefined. Find the bug.
- Lab
Counter
A function that returns a function with memory.
- Boss
The Spy
He wants to read the diary. Three lives, eight questions.
Chapter 13
A function that calls itself: the base case, the recursive step, the call stack — and why folders, menus and comment threads love recursion so much.
- Tale
A parcel inside a parcel
A function calls itself: base case, recursive step, nested arrays and trees.
- Why?
Why doesn't recursion go on forever?
The call stack, every call's own variables, and why trees ask for recursion.
- Workshop
Byte's cloud
Size, file count, depth, a file list and a path to a file — five recursive functions for a folder tree.
- Investigation
The case of the missing category
The catalog search only finds top-level categories. Find the bug.
- Lab
Comment counter
How many comments are in a thread in total — replies to replies included.
- Boss
The Endless Nesting Doll
It opens and opens and opens… Find the bottom.
Chapter 14
Methods and this, classes and new, inheritance and prototypes — and why this gets lost when you tear a method off its object.
Reward: Bolt- Tale
Byte's robot factory
Methods and this, classes and new, extends and super, getters and private fields.
- Why?
Why does this get lost?
Why this is decided at call time, and how not to lose it.
- Workshop
The assembly line
A robot from a literal, a Robot class, working with charge, a status getter and a cleaning robot via extends.
- Investigation
The case of the deaf remote
The robot remote crashes on the very first press. Find the bug.
- Lab
A cart class
A Cart class with methods, getters and each cart's own item list.
- Boss
Rusty Megabot
A rebellious robot keeps mixing up this. Reprogram it.
Part 4 · Real programs
Chapter 15
What happens when code breaks: kinds of errors, throw, try...catch...finally, and how to keep one failure from bringing down the whole app.
Reward: Inspector's hard hat- Tale
An inspection at the warehouse
Runtime errors, throw, try...catch and finally.
- Why?
Why is crashing better than staying quiet?
Why an error with a loud message beats a program that "sort of works".
- Workshop
Cargo inspection
Check, reject and read invoices — four steps with errors.
- Investigation
The case of the white screen
After a failure the app shows a white screen: the settings became undefined. Find the bug.
- Lab
A safe JSON.parse
Parse JSON, and if it's broken, return a default.
- Boss
The Exception
It flies out of nowhere. Catch it.
Chapter 16
How to wait for things that don't arrive at once: promises, async/await, handling rejections and waiting in parallel.
- Tale
The pizza is on its way
setTimeout, promises, async/await, try...catch, Promise.all, a timeout with Promise.race and cancelling with AbortController.
- Why?
Why doesn't setTimeout(…, 0) fire at once?
The event loop: why "in 0 milliseconds" means "after all the current code", and why try without await catches nothing.
- Workshop
Byte's pizzeria
Delays, cooking, parallel orders, a timeout, retries and cancelling — seven steps with promises.
- Investigation
The case of "0[object Promise]"
Instead of a total, the cart shows "0[object Promise][object Promise]". Find the bug.
- Lab
All the prices at once
Load the prices in parallel and wait for all of them.
- Boss
The Endless Spinner
The spinner spins and spins. Find out what it's waiting for.
Chapter 17
Bringing it all together: objects, arrays, methods, errors and async — in one small but real shop.
- Tale
How a shop is built
How to split a program into data and small functions that pass results to each other.
- Why?
Why build a program from small functions?
Why one big do-everything function is worse than ten small ones.
- Workshop
Building the shop
Cart, total, promo codes, delivery, amount due and the order — six steps, the whole program.
- Investigation
The case of the invisible discount
In the shop window, the old and new prices are the same — there's "no" discount. Find the bug.
- Lab
Order total
Compute an order's cost: price × quantity for each line.
- Boss
Production
The last boss. Everything you've learned — against it.
Part 5 · JavaScript in the browser
Chapter 18
How the browser turns HTML into a tree of objects, how to find an element in it, change its text, create a new one — and draw a page from an array of data.
- Tale
A website for the Purrfect Café
The DOM tree, querySelector, textContent, createElement, classList and dataset.
- Why?
Why is innerHTML dangerous?
How innerHTML differs from textContent, what XSS is, and why frameworks escape everything by default.
- Workshop
The Purrfect Café menu
One menu item, a list from data, sold-out dishes, a counter and a category filter — five steps on a real page.
- Investigation
The case of the multiplying reviews
Three reviews, six items in the list. The counter is honest, the list isn't.
- Lab
Cats looking for a home
Draw a list from an array of objects — with exact markup, classes and data-id.
- Boss
The Crooked Selector
He hides elements, slips you null and dreams of innerHTML.
Chapter 19
How a page answers clicks, typing and keys: handlers, the event object, bubbling and delegation, one listener for a hundred buttons.
- Tale
The shop window that purrs
addEventListener, the event object, state and re-rendering, bubbling, preventDefault.
- Why?
Why does a click bubble?
The three phases of an event, where they came from, why delegation is cheap, and why stopPropagation is dangerous.
- Workshop
The toy shop window
Likes, favourites, a delegated cart, live search and keyboard shortcuts in five steps.
- Investigation
The case of the deaf buttons
New toys in the catalog can't be bought. Find out why their buttons don't hear clicks.
- Lab
Tabs
"About / Delivery / Reviews" tabs on a single listener.
- Boss
The Red Dot
It darts around the page and scrambles events. Catch it.
Chapter 20
How to read what the user typed, why a field always gives you a string, why submit handlers call preventDefault, how to collect data with FormData and show clear error messages.
Reward: Fluffy- Tale
An entry for the show
<form>, value and checked, the submit event, preventDefault, FormData and a button you can't press twice.
- Why?
Why does a form reload the page?
Forms are older than JavaScript: what the default submission really does, why preventDefault exists and why checking in the browser isn't protection.
- Workshop
Cat show registration
Read the fields, check the age, show errors next to the fields, collect the awards with FormData and submit without a reload.
- Investigation
The case of the eternal kittens
Every cat, even a twelve-year-old, is sent to the kitten ring — and without a name. Find the bug.
- Lab
Joining the club
A sign-up form: check five fields, show the errors and don't reload the page.
- Boss
The Spam Bot
It's flooding the show with fake entries. Each right answer closes another loophole in the form.
Chapter 21
How a page talks to a server: URLs, HTTP methods and status codes, fetch and res.json(), sending JSON, checking res.ok, and the "loading / error / empty" states.
- Tale
A call to the warehouse
Client and server, URLs, HTTP methods and status codes, fetch, res.json() and a POST with JSON.
- Why?
Why doesn't fetch fail on a 404?
How "the server answered with an error" differs from "there's no answer at all", and why you check res.ok.
- Workshop
The fish warehouse catalog
Loading a list, a getJSON wrapper, a POST order, page states and parallel requests — five steps with fetch.
- Investigation
The case of the fish named undefined
The fish card says "undefined: undefined kg". Find the bug.
- Lab
A customer's orders
Two requests in parallel, checking the responses, and an order summary.
- Boss
The Moody Server
It answers in codes, loses bodies and drops the line. Strike a deal with it.
Chapter 22
How to save data so it survives a page reload: localStorage, strings and JSON, defaults, corrupted data — and what must never be kept in the browser.
- Tale
Memory after a nap
setItem, getItem, removeItem, strings only, JSON, null for empty keys, and what not to put in the browser.
- Why?
Why does localStorage only store strings?
Where Web Storage came from, why it's synchronous and small, and why you pack objects yourself.
- Workshop
Settings that survive a nap
A theme, a wake-up counter, a list of favourite things and a small safe store — five steps with localStorage.
- Investigation
The case of the cart that crashed after a reload
The cart works until you reload the page. Then — SyntaxError. Find the real culprit.
- Lab
Recent searches
A list of the latest queries that survives a reload and isn't afraid of junk.
- Boss
The Vacuum of Oblivion
It sucks up everything that wasn't saved properly.
Chapter 23
We build a real app out of everything in the browser part: the DOM, events, forms, fetch and localStorage. The big idea: the UI is drawn from data.
- Tale
How a real app is put together
State, render(), handlers, saving and the server — the five parts of any front end.
- Why?
Why draw the UI from data?
Two truths, a predictable screen, and the idea React is built on.
- Workshop
Building the to-do list
State and render(), the form, ticks, deleting, filters, localStorage and the server — seven steps to a real app.
- Investigation
The case of the vanishing ticks
The tick goes on, but the counter doesn't move, and after a delete all the ticks are gone.
- Lab
Filtering to-dos
Draw the to-do list by a filter and say how many are shown.
- Boss
The Living Page
The final boss of the browser part: the DOM, events, forms, the network and storage — all mixed up.
Part 6 · How real projects work
Chapter 24
How to split a big program into files: named and default exports, as and import * as, each module's own scope — and why bundlers exist.
- Tale
The two-thousand-line file
export and import, the default export, renaming, module scope, project structure.
- Why?
Why a bundler, if the browser understands import?
What Vite and webpack do with your modules, and why they didn't disappear when browsers learned import.
- Workshop
The shelter moves house
A cat shelter's program lives in one file. Let's split it into modules in five steps.
- Investigation
The case of the checkout that couldn't count
After yesterday's refactoring, checkout crashes with "total is not a function".
- Lab
The cat cafe receipt
Split a receipt into three modules and assemble it in main.js.
- Boss
The Spaghetti Monster
The two-thousand-line file came alive and doesn't want to be split.
Chapter 25
What a package is, why package.json and package-lock.json exist, how to read versions like ^1.2.0 — and why every dependency is someone else's code living in your project.
- Tale
Three days on a calendar
Packages, npm, package.json, semver versions and how to choose dependencies.
- Why?
Why is `node_modules` so heavy?
Transitive dependencies, deduplication, lockfiles and the small-packages philosophy.
- Workshop
Mini npm
Parsing a version, comparing, ^ and ~ ranges and picking the best version — the way npm does it.
- Investigation
The case of the eternal 1.9.0
The update bot can't see new versions and suggests going backwards. Find the bug.
- Lab
New version
Bump a package version before publishing: patch, minor or major.
- Boss
The Typosquatter
He publishes packages with typo names and waits for your mistake.
Chapter 26
How to hunt bugs with a method instead of guesswork: reproduce, read the error and the stack trace, form a hypothesis, check it, narrow down the suspects, fix the cause and lock it in with a test. And why things crash somewhere other than where they broke.
- Tale
The detective's method
Seven steps of debugging, reading errors and stack traces, labeled console.log, debugger and the rubber duck.
- Why?
Why isn't the bug where it crashed?
Symptom and cause: how undefined and NaN quietly travel through a program, and why you search against the flow of data.
- Workshop
Five tickets
An off-by-one, NaN from a missing field, a lost this, a mutated array and async ordering — five bugs in Byte's blog.
- Investigation
The case of the missing customers
The report crashes in formatLine. But formatLine is innocent.
- Lab
The first bad commit
A binary search over history — what git bisect does.
- Boss
The Heisenbug
A bug that vanishes the moment you look at it. Only method, no guessing.
Chapter 27
How to write a check once and repeat it in seconds: test and expect, edge cases, errors and async code, and how to tell whether the tests themselves are worth anything.
- Tale
Who checks the checkers
What a test is, expect and its matchers, edge cases, toThrow, kinds of tests and TDD.
- Why?
Why don't green tests mean the code works?
Tests only check what you thought of. Coverage, mutants, and tests that repeat the bug.
- Workshop
Mutant hunt
Five test suites for Neurocat's code: usual cases, rules, edge cases, errors and async code.
- Investigation
The case of the green tests
The shipping tests are green, yet customers pay for shipping that should be free. Fix the tests.
- Lab
Tests for a password
A test suite that passes the correct code and catches every mutant.
- Boss
The Mutant King
He knows every way to break code quietly. Your tests have to notice.
Chapter 28
How to never lose work again: commits, branches, merges and conflicts, GitHub and code review, undoing things honestly — and why git stores snapshots, not changes.
Reward: Time goggles- Tale
The lost Tuesday
Repository, staging and commits, branches and merges, GitHub and pull requests, .gitignore and undoing safely.
- Why?
Why does git store snapshots, not changes?
Content addressing, hashes, cheap commits and 41-byte branches.
- Workshop
Build your own mini-git
A hash, commits, history, diff, branches and switching — six steps to your own git.
- Investigation
The case of the rewritten history
Every saved version of a note shows the latest text. History changes after the fact!
- Lab
Resolve the conflict
The editor's "Accept current / incoming / both" buttons, built by hand.
- Boss
The Great Conflict
Two branches, one line — and angle brackets crawl out of the file.
Chapter 29
Everything at once: modules, fetch, the page, forms, localStorage, errors and tests — in one real app. Plus how to plan a project, show it to the world and build it together with an AI assistant.
Reward: Graduate's laurels- Tale
How a real app gets planned
Requirements → data → modules → UI states → edge cases → tests → shipping. And what a portfolio project should show.
- Why?
Why split a project into layers?
Data, logic and interface kept apart. For the tests, for swapping the API, and for your own nerves.
- Workshop
Building the weather app
Five modules, a fake server and a live page: formatting, an API client with errors, states, the form and recent cities.
- Investigation
The case of yesterday's weather
Two quick searches — and the wrong city on screen. A request race.
- Lab
A report for several cities
Weather for several cities at once: parallel requests, partial failures and the warmest city.
- Boss
His Majesty the Release
The course's final boss. Questions from all twenty-nine chapters.