From zero JavaScript to a live review list — the language, the tools, and the async data path
2026-10-18
In Session 1 you drew a review card: HTML for structure, CSS for appearance, and data typed by hand into the markup. A real storefront has no author pasting reviews into HTML — it asks for the data when the page opens and builds the cards on the spot. That shift, from a drawn page to a page that computes itself, is JavaScript, and it is what this lecture is for.
The price of the deal: JavaScript has known traps — coercion, mutation, asynchrony. We treat them as part of the language, not as advanced topics.
The ground
The machinery
The payoff
Every part is mandatory core. When you finish reading, you go to webdev_02_P_JavaScriptForReact.qmd, the paired practice file where you build the review list yourself.
JavaScript runs in more than one place. Two matter to this course:
Node does power your tooling — npm and Vite run on it — but that is tooling doing a job for you. The language you are learning lives in the browser, and the browser is where you will watch it work.
Open DevTools with F12 (macOS: Cmd+Option+I; Windows/Linux: Ctrl+Shift+I) and select the Console tab. It is your debugging instrument: it shows what your code prints and every error the browser catches.
console.log prints in plain text — your everyday probe. console.error prints in red, reserved for real failures, and it is also how async work that fails with nothing catching it reaches your eyes. Open the Console before you suspect the page of lying to you.
The rendered page can mislead you; the Network tab cannot. Open it, click the Fetch/XHR filter, and every fetch the page performs shows up as a row:
200 means the server found the file and sent it; 404 means the request reached the server but nothing lives at that address — a typo, a wrong path, a missing file. All course long, when a list renders empty, this tab tells you whether the problem is the request or the code handling its answer.
Double-clicking an HTML file opens it at a file:// address. An origin is the scheme + host + port of an address — for example http://localhost:5173 — and from the file:// origin the browser refuses to let your code read a local JSON file: the fetch is blocked, the list renders empty, and the Console shows an error. This is the same-origin rule, not a bug in your code — and no change to your JavaScript will fix it.
The fix is serving the page over HTTP, which is exactly what the Vite dev server does:
npm run dev starts a local HTTP server that serves your project at http://localhost:5173, with hot reload on top: save a file, the browser updates. You never configure Vite in this course — you start it and point your browser at it.
The frontend/ project comes from the course starter: you cloned ebpro/fullstack-minimal-app — there is no npm create vite step here — and the files under frontend/public/prototypes/ are the ones you generate yourself during the practice session.
Vite serves your code, and everything inside public/ at the root of the site — with no public/ segment in the URL:
Follow the chain: the page lives at http://localhost:5173/prototypes/review-list.html; its code calls fetch('./reviews.json'); the browser resolves that relative URL against the page’s own address, and the server answers from public/prototypes/reviews.json because public/ is what it exposes. This mechanism is what makes your practice file’s data reachable.
Everything you need to know about npm in this course fits on one screen. package.json holds the project’s metadata, its scripts, and its dependency lists:
Two commands, and you are done: npm install reads the dependency lists and materializes them into node_modules/; npm run dev executes the dev script — the Vite server from the previous slide.
Tip
An assistant told you: “just double-click the HTML file, it’ll work.” Predict what this line does when the page is open at a file:// address. The practice file tells you to use the dev server; opening the prototype both ways is a lecture-side demonstration we run once here — watch the Console and the Network tab as we do it:
AI models get this wrong often — your job is to check.
The claim is false. Over file:// the browser refuses the read: the fetch fails, the Console shows an error, no row succeeds in the Network tab, and the list renders empty. Over http://localhost:5173/prototypes/review-list.html the identical code works. The fix is where the page is served from — never a change to the JavaScript.
Reach for const first, and for let only when the value must be reassigned.
Both are block scoped: a binding lives only inside the nearest braces.
The older var keyword still appears in legacy code and in AI-generated output. Read it, never write it: it ignores those braces and hides bugs that are hard to trace. Default to const, treat let as the exception.
Seven kinds of value cover most of what you will handle: string, number, boolean, null, undefined, plus the composites object and function.
const name = "Maya" // string
const rating = 4.5 // number: one type for all numbers
const published = true // boolean
const empty = null // deliberately empty, by decision
let draft // undefined: no value yet
const scores = [1, 2, 3] // object (an array is an object)
function double(n) { return n * 2 } // functionundefined is what the language hands you: an unassigned variable, a missing argument, a property that does not exist. You never assign it yourself. null is your decision that a slot is intentionally empty. The difference is intent, not mechanics.
JavaScript silently converts types when an operator meets mixed operands. This is coercion, and + is where it bites first.
The rule: when either side of + is a string, the other side becomes a string too. Every other arithmetic operator converts both sides to numbers. A "2" from a form field added to a 3 yields "23", and nothing warns you.
JSON is text, so numbers arrive as strings and conversion is your job.
Number("4.5") // 4.5
parseInt("5px", 10) // 5 always pass the radix: the 10 says base ten
String(5) // "5"
Number.isInteger("5") // false the check does not coerce
Number.isInteger(5) // true
(3.005).toFixed(2) // "3.00" a string, not a number
Number("abc") // NaN conversion failed
NaN + 1 // NaN the poison spreads
Number.isNaN(NaN) // true the only reliable testparseInt stops at the first character it cannot read, so always pass the radix: the 10 says base ten. toFixed(n) rounds for display and returns a string. NaN is worse: it spreads through every later operation and never recovers. Why this matters: the backend session guards a rating with Number.isInteger(r.rating), unreadable unless you know "5" is not 5.
== compares after coercing both sides, === compares without coercion.
The coercion table behind == is long and full of exceptions, and nobody carries it in their head. Use === and its negation !== everywhere and the question never comes up again.
Backticks build strings that embed any expression inside ${ }.
Between the braces goes an expression, not merely a name. Backticks also keep line breaks, which is how multi-line text is written:
Forward note: in next session’s JSX, ${ } does not work inside markup; JSX embeds expressions with single braces, so that same value is {rating}.
A declaration is hoisted: you may call it before its line appears.
A function expression stores the function in a variable; no hoisting.
An arrow function is the compact form. When the body is a single expression, the implicit return applies: no return keyword.
The trap: an arrow body that starts with { is read as a block, not an object literal. Wrap the object in parentheses.
A function is a value like any other: store it, pass it, return it.
A callback is a function you hand to someone else’s code so that code can call it back at the right moment. Note that both the React and the Express sessions use this word freely without ever defining it.
A higher-order function takes and/or returns functions.
The returned function keeps n alive after makeCounter has returned. That pairing is a closure: a function bundled with the scope of its birth. Imagine setTimeout(c, 1000) (it calls c after one second — the timer is the vehicle here, not the topic): when the call finally happens, n is still there, and still private to this one closure.
Next session’s React code uses exactly this shape for a cancellation flag, and Express uses it for middleware.
An if is a statement: it produces no value. The ternary and && are expressions: both produce a value. That is why UIs are written with them — you cannot paste a statement into the middle of a value.
Both rely on truthiness: the falsy values are false, 0, "", null, undefined and NaN; everything else is truthy.
One caveat: && forwards the falsy left side, so 0 && 'x' yields 0, not 'x'.
A guard clause checks the bad case first, returns immediately, and keeps the happy path flat instead of nested.
Each condition is a gate; reading top to bottom, the interesting line is never buried inside braces.
Tip
Write down what each line produces before reading the answers.
Answers: 4.5 (a real number); '41' (+ prefers string concatenation); 8 (* forces both sides to numbers); 5 (parses the leading digits); '3.00' (a string — the stored binary value rounds down); NaN (NaN poisons every arithmetic operation).
An assistant gets these confidently wrong, and checking takes ten seconds.
Two counters built by one factory, with the calls interleaved. Predict each result.
Tip
Answers: 'a:1', 'a:2', 'b:1', 'a:3' — each factory call creates a separate environment, so the two closures never share ticks.
Same rule as the last checkpoint: verify the AI’s answer by running it.
Everything later in this part rests on two structures: the object, which holds a single record, and the array, which holds a collection of them. This first half stays with standalone records; the second half turns to arrays.
An object literal is a comma-separated list of key: value pairs between braces. It is how JavaScript writes one record of data, with a name attached to each value:
The second literal uses the shorthand: when a variable already holds the value, writing its bare name as the key stands for the pair { review_id: review_id }. Same record, less typing — and still no array in sight.
Once a record exists, its fields are reachable two ways:
Dot is what you will write almost always: shorter and easier to read. Bracket access exists for the case where the key name is itself the content of a variable. Note that r.key looks for a field literally named key — the dot never evaluates what follows it.
Object keys are strings, even when they look like numbers; a numeric key is converted the moment it is stored:
The two spellings collide on purpose: in { 1: "a", "1": "b" } a single field survives, holding "b". Retain the rule, not the trick — obj[1] and obj["1"] address the very same field, because a key is always a string.
Records arrive as const bindings, yet the whole practice file is about producing a new record from an old one. The tool is the spread, ..., used inside a fresh literal:
The two logs are the point of the slide: the override value (4) differs from the original (5), and the original still reports 5. The spread built a new object instead of changing the old one — the immutability discipline named in the part title.
Note
Used over an array, ... does the same job: a fresh shallow copy of the items. It will be shown there when arrays arrive, in the second half.
Everything above describes a single record. The working set for this course is that record, six times, in an array:
const reviews = [
{ review_id: "AMZ_0001", source: "Amazon", author: "sam", rating: 5, title: "Fast and quiet", body: "Used it daily for a month.", created_at: "2026-03-14", verified_purchase: true },
{ review_id: "BBY_0001", source: "BestBuy", author: "jules", rating: 4, title: "Good value", body: "Minor rattle at high load.", created_at: "2026-04-02", verified_purchase: true },
{ review_id: "WMT_0001", source: "Walmart", author: "ana", rating: 1, title: "Broke on day two", body: "Returned it.", created_at: "2026-02-27", verified_purchase: false },
{ review_id: "AMZ_0002", source: "Amazon", author: "toma", rating: 3, title: "Does the job", body: "Nothing special.", created_at: "2026-05-19", verified_purchase: true },
{ review_id: "BBY_0002", source: "BestBuy", author: "noor", rating: 2, title: "Too loud", body: "Fine at idle, awful upstairs.",created_at: "2026-01-08", verified_purchase: false },
{ review_id: "WMT_0002", source: "Walmart", author: "kiro", rating: 5, title: "Better than hoped",body: "Second one for the office.", created_at: "2026-06-01", verified_purchase: true },
];This is one valid instance of the shape the practice file asks you to generate: your own file will hold different values, the same shape, and the same eight fields. Two naming rules never vary: the text field is body, never content, and review_id is a string, never a bare number.
The practice file gives you clean, complete records. This lecture adds a second, smaller array of three deliberately messy ones — dirtyReviews — because real review feeds are not clean, and you need a place to practice guarding before you render.
const dirtyReviews = [
{ review_id: "AMZ_9001", source: "Amazon", author: "bot5", rating: "5", title: "AMAZING!!!", body: null, created_at: "2026-06-11", verified_purchase: true },
{ review_id: "BBY_9002", source: "BestBuy", author: "", rating: 4.5, title: "ok", body: "", created_at: "not-a-date", verified_purchase: true },
{ review_id: "WMT_9003", source: "Walmart", author: "ana", rating: null, title: "no rating", body: "?", created_at: "2026-06-30" },
];Warning
This is experiment data — never put it in your reviews.json. These three records, AMZ_9001, BBY_9002 and WMT_9003, each break a rule: a rating stored as the text "5", a rating of 4.5 where whole stars are expected, an empty author, and verified_purchase missing entirely from the last record.
reviews and dirtyReviews are declared exactly once, in this file, and both arrays are reused by name from here on.
forEach runs a side effect per element and returns undefined.
map builds a new array by transforming every element.
filter builds a new array with only the elements that pass a test.
Load-bearing: none of the three touches reviews itself. labels and fiveStars are new arrays; reviews keeps its six records in file order, ratings 5, 4, 1, 3, 2, 5. Hold that sentence — it pays off two slides from now.
sort() cannot rank reviews on its own. It takes a comparator (a, b) and reads only its sign: negative puts a first, zero keeps the pair, positive puts b first.
Recency needs one line of recipe:
new Date(text) builds a Date from an ISO timestamp; subtracting two Dates gives milliseconds. Take the recipe as written — the machinery behind new is out of scope here.
And note what sort() returns: the same array it was given — which is why reviews.sort(...).map(...)-style chaining reads left to right.
Two slides ago, forEach, map and filter never touched reviews. sort() does the opposite: it reorders the array in place.
const does not protect you. It fixes the binding — the name cannot be re-pointed at another array — and says nothing about the contents. Reassigning reviews is an error; reordering it is legal and silent, and every later use of the name sees the new order.
When the file order still matters, sort a copy:
slice() with no arguments is a fresh shallow copy; the mutation lands there.
[...xs] — three dots over an array — is a fresh shallow copy: a new array holding the same elements.
const sorted = [...reviews].sort(byRating);
const proposed = { ...reviews[0], rating: 1 };
console.log(reviews.length); // 6 — the source never shrank
console.log(reviews[0].rating); // 5 — still 5: the override differs on purpose
console.log(sorted === reviews); // false — the copy is not the sourceThe rule for this whole part: never sort or edit reviews — edit a copy.
Silent damage, the alias.
reviews comes out reordered although you never called sort on it: alias is not a copy, it is reviews wearing a hat — and the corruption is quiet.
Loud crash, reassignment.
This throws a TypeError — the binding is const. And filter built a new array and left the source untouched: the throw is the good case, it stops you where the alias let damage through.
reduce walks a list carrying one value — the accumulator — to the end; here a plain object counting reviews per source.
Forget return acc and the next step receives undefined.
for...of walks the values of any iterable; today that means arrays — key/value iteration of objects is the next part.
Each step binds one full review object; prefer it over an index loop when you do not need the index.
Start from a fresh page so reviews holds ratings 5, 4, 1, 3, 2, 5, and write down three predictions before running.
Answers: [ 5, 4, 1, 3, 2, 5 ], then [ 5, 5, 4, 3, 2, 1 ], then true. The function edits its argument — result === reviews proves it — and the source order is gone until you reload. Fix: return [...list].sort(...) with the same comparator; then reviews never moves.
Destructuring reads values out of an array or object in a single line. Four shapes cover everything in this session.
You have seen this shape in React examples. It is the array-pair pattern above, applied to the two-element array that React hands you.
This is React’s syntax arriving later in the course — recognition only. Nothing here needs to be writable yet; Session 3 owns it.
This slide is the home of the ||-as-default idiom; the histogram slide that follows may use it freely.
|| falls back for every falsy value — 0, "", false, null, undefined, NaN. When any of those is a real datum, that is a trap. ?? falls back only for null and undefined, so a rating = 0 stays 0.
Note
Read ??= as: “if the left side is still nullish, assign the right side.” It is shorthand for x = x ?? y, not a new kind of value check.
Until now our keys were known in advance; a histogram takes its keys from the data itself. r.source is an expression evaluated at each turn of the loop, and bracket access accepts exactly that.
The first "Amazon" reads undefined, falls back to 0, stores 1; the second reads 1 and stores 2. The two-step spelling below is the one you will meet most often, using the same ??= seed as one slide earlier — and both loops end in the same state, Amazon 2 · BestBuy 2 · Walmart 2: three numbers and no array, because we count here, we do not collect.
Object.entries turns an object into an array of [key, value] pairs, Object.fromEntries turns such an array back into an object:
entries is the bridge that lets a keyed object pass through array land and come back whole: recognise the round-trip for now. One more name to file away, new Map — a keyed collection you will meet again, not today.
dirtyReviews stands here for a list whose first record has no author at all. ?. asks one question: is what sits on my left there at all? If any step is null or undefined, the whole chain short-circuits to undefined instead of throwing — you will read this pattern long before you need to write it. Division of labour: ?. prevents the crash, ?? supplies the default.
The same reviews, a merged-too-fast loop, one console.log:
Warning
Predict first. Does this print undefined, NaN, or a number? Then run it and compare.
On the first record broken["Amazon"] is absent, so the update computes undefined + 1, which is NaN. Nothing crashes — NaN is a number — and every later turn keeps adding to it, so all three keys end at NaN. One line fixes it, placed before the accumulation:
A module is a file with a scope of its own. One concern per file: the list renderer here, the rating widget there, the formatting helpers in a third. The browser loads only what the page references, and each file states what it needs from elsewhere instead of hoping it is already in memory.
Without import, every top-level const in every file lands in one shared namespace. Two files may both declare items and the second overwrites the first, quietly. Modules make that collision impossible.
One default per file, any number of named exports. The default names the concern; the named ones are what other files may borrow.
A default import may be called anything you like; a named import must use the exported name, unless you rename it with as. The namespace form reads well in a console and poorly in committed code.
Rule one. When the browser loads a module directly, without a bundler, the specifier is a URL, so it carries the extension.
A missing extension resolves to nothing: Failed to resolve module specifier in the console, an empty page, no other explanation. A bundler or dev server (your Vite and React sessions) resolves extensionless specifiers for you.
Rule two. Node-side tooling reads package.json before it reads your code.
Then import inside a .js file throws SyntaxError: Cannot use import statement outside a module. Both mistakes stay invisible in the editor.
This session’s prototype loads as a plain script, just before </body>:
A plain script has no module scope and no import: everything lives in one file, helpers and state and rendering side by side. That is a deliberate choice, not an oversight - one file is short enough to write on a whiteboard, and it delays nothing the concept needs.
The practice task is written the same way on purpose, so it cannot surprise you. Add import to that file and the browser refuses it, naming the missing attribute:
Older tutorials, and a good share of AI-generated examples, use the system that came before modules: require and module.exports. It runs under Node, never in a browser.
Read a require in someone else’s answer as a sign the answer is dated. The vocabulary here is import and export and nothing else.
import.meta is a built-in object the module system hands to every file, and Vite hangs env off it. It is the only route from your configuration to code running in the browser.
The VITE_ prefix is what exposes a value to client code: without it the value never reaches the browser at all. Anything sent there is public, so this channel carries endpoints, names, and flags - never credentials.
Everything here is synchronous: the reviews array already sits in memory and the job is to turn each record into visible markup. The DOM is that page held in memory as a tree of JavaScript objects — elements with properties and methods, reachable from one global, document. Find the container, make a child per review, attach it: that is the whole idea.
getElementById is the plain choice when the id is known; querySelector earns its keep for a CSS selector (".card", "#review-list .card") and returns the first match only. A wrong id gives null — the classic typo:
Create a detached element, set its content, mount it — that loop is practice Task 1. The page’s <style> block is what turns a plain div into a visual card; that CSS is the practice file’s job, not this lecture’s.
// reviews: the lecture data — six records, fields as in the schema table
for (const r of reviews) {
const card = document.createElement("div")
card.className = "card"
const heading = document.createElement("h3")
heading.textContent = r.title
const stars = document.createElement("p")
stars.textContent = "★".repeat(r.rating) + " · " + r.author
const body = document.createElement("p")
body.textContent = r.body
card.appendChild(heading)
card.appendChild(stars)
card.appendChild(body)
list.appendChild(card)
}textContent inserts text; innerHTML parses markup into nodes. With a hostile record, that difference is the whole story:
One displays a string, the other executes it: parsed markup is code. The rule, as policy and not style:
Any string that came from outside your code goes through
textContent.
Titles, form input and API payloads are outside your code; innerHTML is for markup you wrote — security, not style.
A template literal is a handy way to write the card shape; it is unsafe the moment it interpolates text authored by someone else, so the review’s own fields go through textContent.
Tip
An assistant proposes a shorter loop; predict what each pass does to cards already there:
+= re-serialises the container, appends, re-parses: every earlier node is destroyed and replaced by a new object, so a listener attached before is gone.r.title was never trusted and innerHTML parses whatever it holds.Verdict. Rejected. Create, fill with textContent, mount with appendChild. Ask an assistant to defend innerHTML += and it will produce this loop; your job is to see the cost and the hole rather than run it.
addEventListener attaches a handler; the browser calls it with the event object. Two names cover this course: "change" fires when a value is committed, "input" fires on every keystroke in a text field. Every control in this session is a <select> — #source-filter and the #sort-select Task 3 adds — so both bind "change". A text search box would fire "input", useful to know, but that control is not part of this task.
event.target is the node the event fired on, .value its current content — the exact expression the framework session leans on dozens of times. The select’s first option carries value="all", so “no filter” is a value you must test for, not an absent one.
.value is always a string, even on a numeric field, so "4" compared with a number misbehaves: Number(event.target.value) fixes it, as the coercion part explains. In a form, event.preventDefault() cancels the default submit-and-reload so the page stays.
A script sees only what the parser has built. review-list.js loads as a plain <script> just before </body>, so every element above it exists — but one in <head> would read null for #review-list. The guard is one line and makes ordering irrelevant:
Find, create, fill with textContent, mount with appendChild, listen with addEventListener: that is practice Task 1. In the next part the array arrives over the network instead of being hardcoded, and nothing else changes. Deferred: event delegation and localStorage live in webdev_02_L_02_JavaScriptAdvanced.qmd.
Everything so far ran over data you already had. A JSON file lives one HTTP request away, and a request takes time. Your code cannot spend that time waiting: JavaScript runs in the same thread that paints the page and answers clicks, so a blocking read freezes the tab — broken software, not slow software. So JavaScript never waits, it defers: you hand the runtime some work plus a note of what to do when it finishes, and your code carries on. ### The event loop: one lane, callbacks queued
Picture one worker and one inbox. The worker takes a task, runs it to completion, then looks at the inbox: nothing interrupts a running task, nothing queued starts before it returns.
Long work never interrupts short work — one busy loop hangs a whole page. And order is not causality: logging after something else is an accident, not a guarantee. ### Promises: a placeholder for a value you’ll get later
A promise stands in for a value that is not there yet. It sits in one of three states and moves once, never backwards: pending (waiting), fulfilled (done, holding the value — for fetch, a Response), rejected (holding an error). fetch hands you one immediately, fulfilled when the headers land, not when the body is parsed: a receipt, not a parcel. ### async / await: making async read top-to-bottom
await means pause this function, resume it when the promise settles, hand me the value. The function pauses; the lane does not — everything else runs on.
An async function always returns a promise, so its caller must await it; and await is legal only inside one, or at the top level of an ES module (the type="module" form). ### fetch is not done when it returns — and it does not throw on 404
The most expensive misunderstanding in this lecture. fetch settles as soon as the headers arrive; the body is still in transit, which is why response.json() is a second await. And a 404 is not an error to fetch: a 404, a 500, a missing file — all arrive as a healthy Response whose response.ok is false. fetch rejects only when the request could not be made at all, so nothing warns you: your own if is the only guard.
Important
An assistant that omits the response.ok check has not written cautious code: it fails late and blames the wrong file. Check every generated fetch against the three lines below.
Copy this block unchanged for the rest of the course. The check must be explicit because a status arrives as data, not as an exception: nothing throws on its own. Carrying status and URL makes a failure name itself — HTTP 404 for http://localhost:5173/prototypes/reviews.json tells you what to fix, Unexpected token '<' does not. Only now do you have a value worth rendering with createElement, textContent and appendChild: the DOM part is the sink, not the console. ### 🔎 Checkpoint — find the bug: the missing response.ok check
An assistant wrote this. The list comes out empty and the console blames the JSON.
There is no such file, so the dev server replies 404 with an HTML error page, and fetch does not throw on that. response.json() tries to parse <!DOCTYPE html> and dies on its first character: SyntaxError: Unexpected token '<'. The error names JSON; the bug is a filename. Verify the claim “fetch throws on a bad status”: false — every silently-empty list you debug from here on is built on that falsity, and the fix is the ritual. ### try / catch / finally: the loading-flag pattern
try runs the risky code, catch runs only if something threw, finally runs either way — success, failure, even an early return. That is why a loading flag belongs in finally.
let loading = true
try {
const response = await fetch('./reviews.json')
if (!response.ok) throw new Error(`HTTP ${response.status} for ${response.url}`)
const data = await response.json()
document.getElementById('review-list').textContent = `${data.length} reviews`
} catch {
document.getElementById('review-list').textContent = 'Could not load the reviews.'
} finally {
loading = false
}catch { with no parentheses is the binding-less form, for when you do not need the error object. Your plain <script> prototype has no top-level await, so this code lives inside an async function you call, or inside a DOMContentLoaded listener. ### Bare array or { data, meta } envelope? Know which one you’re holding
Two shapes will cross your path and they are not interchangeable: the left is your file today, the right a shape preview of what a later session serves.
reviews.json, today a later API response
[ {
{ "review_id": "AMZ_0001", … }, "data": [ { "review_id": "AMZ_0001", … },
{ "review_id": "BBY_0001", … } { "review_id": "BBY_0001", … } ],
] "meta": { "total": 2 } }
data.length → 2 data.length → undefined (silent!)
data[0].rating → 5 data[0].rating → TypeError
data.data.length → 2The right column fails quietly on .length and loudly on [0], and your practice file warns about this exact switch. Rule: read the shape before you index it — inspect the response in the Network tab and write the index to match its first character. ### response.json() vs JSON.parse
response.json() is a method on the response and returns a promise — write await. JSON.parse is a function on a string and returns the value at once. Forget the await on json() and data.length is undefined, because data is a pending promise. ### Recognition only: .then, Promise.all, and the async IIFE inside useEffect
You will meet all three in the next session; you do not need to write any of them today.
.then(...) is the older spelling of await — the same promises chained by hand. Promise.all([...]) starts independent fetches in parallel and waits for the whole group.
useEffect(() => {
let cancelled = false
;(async () => {
const response = await fetch('./reviews.json')
if (!response.ok) throw new Error(`HTTP ${response.status} for ${response.url}`)
const data = await response.json()
if (!cancelled) setReviews(data) // only if we still care
})()
return () => { cancelled = true } // React runs this on cleanup
}, [])Look at the last two lines: useEffect returns a function that remembers cancelled, a variable in the scope where it was born, and flips it when cleanup runs. That is the closure from the Language Core part — a function escaped from its birth scope, still holding a live reference to it. This callback is the payoff for that hard work.
Write the order down before you read on.
The answer is A, 1, B, 2, 3. main() runs synchronously up to its first await, then suspends and hands back a pending promise; B is already in the lane and finishes before any continuation resumes. And pending is a promise, not the array — await it. Every “why is my list empty on the first render” you debug is this fact in disguise.
The page fits on one screen: two controls, one empty container, and a plain <script> tag just before </body>, so every element above it already exists when the code runs.
<body>
<select id="source-filter"><option value="all">All sources</option></select>
<select id="sort-select">
<option value="newest">Newest</option>
<option value="oldest">Oldest</option>
<option value="highest">Highest</option>
<option value="lowest">Lowest</option>
</select>
<div id="review-list"></div>
<script src="review-list.js"></script>
</body>The whole design rests on one fact: the page makes a single network call, and everything after it is memory work.
loadAll() is the fetch ritual, copied unchanged, inside the taught try/catch/finally: renderListFailure(error) writes a plain human sentence into #review-list, and finally clears the loading flag either way.
let allReviews = [];
let loading = true;
async function loadAll() {
try {
const response = await fetch('./reviews.json');
if (!response.ok) throw new Error(`HTTP ${response.status} for ${response.url}`);
allReviews = await response.json();
} catch (error) {
renderListFailure(error);
} finally {
loading = false;
}
}The listener redraws from that array and never re-fetches:
A change of source is a change of view, not of data; #sort-select is handled the same way, bound to change.
renderReviews(chosen) touches no network: it copies, filters, sorts, empties the container with replaceChildren(), then rebuilds it with one card per visible review.
const byNewest = (a, b) => new Date(b.created_at) - new Date(a.created_at);
function renderReviews(chosen) {
if (loading) return;
const visible = [...allReviews]
.filter(r => r.source === chosen || chosen === "all")
.sort(byNewest);
const list = document.querySelector("#review-list");
list.replaceChildren();
for (const review of visible) list.appendChild(buildCard(review));
}An assistant wrote the version below. It uses the right ids, builds <div> cards, and — exactly like the real page — its file loads just before </body>, so every element it touches already exists. Everything it does not show is the allReviews binding and the buildCard helper from above, unchanged. There are exactly three bugs.
async function loadReviews() {
const response = await fetch('./reviews.json');
const json = await response.json();
allReviews = json.data;
allReviews.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
renderReviews("all");
}
function renderReviews(chosen) {
const list = document.querySelector("#review-list");
const visible = [...allReviews].filter(r => r.source === chosen || chosen === "all");
list.replaceChildren();
for (const review of visible) list.appendChild(buildCard(review));
}Warning
response.ok check — the very defect the async checkpoint drilled, now hiding inside a bigger draft; the repetition is the point.json.data on a bare array — response.json() already hands you the array itself.allReviews.sort(...) in place — here each call re-parses fresh JSON, so nothing visibly corrupts: it is a latent fault, forbidden by the copy-first discipline, and permanent the moment the array stays in memory and is re-rendered (Task 2).allReviews, the loading flag and what is on screen are separate facts nothing forces to agree.Tasks 2 to 4 of the practice file make you run this loop by hand, once per task.
React inverts the arrangement: the data is kept in one place, and when it changes React re-runs a function whose description of the screen becomes the screen. Session 3 is where you do exactly that, and the vanilla skeleton above is the hand-written machinery it replaces.
This is a checklist of artifacts, not a feeling. Open each one again in the course material and read it line by line. If you can say what each line does and what would change if you deleted it, the Language Core did its job.
[...list].filter().sort() as one pipeline, and why the copy comes firstcount[key] ??= 0 followed by += 1 read as “start an unseen key at zero, then count”({ source, rating }) = req.body read as a binding taken out of an incoming objectconst [rows] = await ... read as array destructuring that skips what you do not useawait it, check ok, only then read the bodyimport and export with an explicit .js specifier, and what the extension provesevent.target.value on a select, and why the result is a string and not a numberA ❌ on any line above is information, not a verdict: name the exact line that is still opaque before you move on.
Three named destinations. Each one is now readable for a specific reason, not in general.
cancelled flag is the closure from the Language Core part; the cleanup return () => {...} is a returned function; useState gives the tuple you previewed; ${} becomes {} in markup.for...of plus the ??= counting idiom from Destructuring, defaults & key-value tools; middleware is a callback with next; the API returns the { data, meta } envelope you learned to check for.None of this is new syntax. It is the same shapes assembled at a larger scale, which is the whole point of the course. Read the practice session first: the two lectures after it make far more sense once you have made the code fail yourself.
Deferred on purpose, never deleted. Every row below is a verified target inside webdev_02_L_02_JavaScriptAdvanced.qmd.
| Deferred topic | Where it waits |
|---|---|
find, findIndex, some, every |
the optional lesson |
Deeper reduce than the accumulator shown here |
the optional lesson |
Full optional chaining ?. |
the optional lesson |
| Deep and nested destructuring | the optional lesson |
localStorage |
the optional lesson |
| Debounce and throttle | the optional lesson |
| Event delegation | the optional lesson |
| The long “why React” walkthrough | the optional lesson |
| Throwing with a useful message, rethrow, and global error handlers | the optional lesson |
Open that lesson when a real task in the practice session or the React lecture needs one of these rows, not before: deferred material reads better when you already have somewhere to put it.
One honest gap: class, this and new are explained nowhere in this course — new Date(...) is handed out as a recipe, and new Map appears at recognition level here and again in the Node/Express session, with no explanation of constructors or object-to-primitive coercion. The optional lesson shows one unexplained class ShoppingCart listing; read it as an illustration, not as something you are expected to learn.
Five sentences you should be able to defend in an exam, with the material closed.
let and const say what may be rebound, and neither of them says anything about the type.event.target.value — because digits inside a string are still a string.sort reorders in place, objects travel by reference, and [...list] is the cheapest defence you have.await hands you a response, not data, and an unchecked ok turns a 404 into a crash three lines later.The lecture ends here; the reading does not. Open the practice session before the next meeting and bring the lines that resisted you.
E. Bruno - JavaScript for React