JavaScript for React

From zero JavaScript to a live review list — the language, the tools, and the async data path

Université de Toulon

LIS UMR CNRS 7020

2026-10-16

🧭 Orientation — Where You Are & What This Lecture Unlocks

Session 1 gave you a picture. This session gives you the behavior.

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 deal: no JavaScript assumed, programming yes

  • No prior JavaScript. Every construct appears here for the first time.
  • General programming literacy. Variables, functions, loops, conditionals as concepts — from any language.
  • Nothing else. You do not need to have used another language’s web stack: no framework background, no HTTP course, no build-tool experience. Where those matter, we explain them from zero.

The price of the deal: JavaScript has known traps — coercion, mutation, asynchrony. We treat them as part of the language, not as advanced topics.

Map of this lecture

The ground

  • 📦 Where JavaScript Runs & the Tools You Use
  • 🎯 The Language Core: Values, Functions, Closures
  • 📚 From records to collections: objects, arrays & the immutability discipline

The machinery

  • 🧩 Destructuring, defaults & key-value tools
  • 🔎 Modules: How Files Find Each Other
  • 📝 The DOM: Turning Data Into Pixels

The payoff

  • → Async & Fetch: The Data Isn’t There Yet
  • 🏗 Putting It Together: The Vanilla Pattern
  • 🚀 What You Can Now Read & Where It Continues

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.

📦 Where JavaScript Runs & the Tools You Use

Two homes: the browser and Node

JavaScript runs in more than one place. Two matter to this course:

  • The browser. Every line you write in this session executes inside your browser tab, next to the page it modifies; the review-list prototype you will read and build is browser code.
  • Node. A program that runs JavaScript on your machine, outside any browser. Later sessions use it to host the Express backend; you do not write Node code here.

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.

Your first instrument: the DevTools Console

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('rating:', 5)
console.error('could not read reviews.json')

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 Network tab: ground truth for every fetch

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:

Name           Status  Type
reviews.json   200     fetch
reviewz.json   404     fetch

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.

Why file:// breaks fetch — and the Vite dev server

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

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.

public/: the folder the browser can reach

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:

frontend/
  public/
    prototypes/
      review-list.html
      review-list.js
      reviews.json

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.

One screen: package.json, npm install, npm run dev

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:

{
  "name": "frontend",
  "scripts": {
    "dev": "vite",         // what npm run dev executes
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {},      // libraries the app imports
  "devDependencies": {}    // tools used while developing
}

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.

✅ Checkpoint — verify the claim: “just open the file”

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:

fetch('./reviews.json')

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.

🎯 The Language Core: Values, Functions, Closures

Declaring: const by default, let when it must change

Reach for const first, and for let only when the value must be reassigned.

const rate = 0.21          // never reassigned
let attempts = 0           // will change
attempts = attempts + 1

Both are block scoped: a binding lives only inside the nearest braces.

if (attempts > 0) {
  const message = "retrying"
}
console.log(message)       // error: message is not defined

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.

The types you will actually meet

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 }   // function

undefined 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.

Coercion: what + and == really do

JavaScript silently converts types when an operator meets mixed operands. This is coercion, and + is where it bites first.

"4" + 1     // "41"   number becomes a string, then concatenation
"4" * 2     // 8      string becomes a number, then multiplication
"a" + 1     // "a1"
"4" - 1     // 3      "-" has no string meaning, so it converts

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.

Coercion in a real data path

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 test

parseInt 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.

=== vs ==: pick one, never look back

== compares after coercing both sides, === compares without coercion.

"4" == 4            // true   the string becomes a number
"4" === 4           // false  different types, no conversion
null == undefined   // true
null === undefined  // false

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.

Template literals

Backticks build strings that embed any expression inside ${ }.

const name = "Maya"
const rating = 4.5
const line = `${name} scored ${rating} out of 5`
const count = `${2 + 3} items`   // "5 items"

Between the braces goes an expression, not merely a name. Backticks also keep line breaks, which is how multi-line text is written:

const notice = `Dear ${name},
your rating of ${rating} was recorded.`

Forward note: in next session’s JSX, ${ } does not work inside markup; JSX embeds expressions with single braces, so that same value is {rating}.

Three ways to write a function

A declaration is hoisted: you may call it before its line appears.

add(2, 3) // 5 — hoisting: this call sits above the declaration
function add(a, b) {
  return a + b
}

A function expression stores the function in a variable; no hoisting.

const addExpr = function (a, b) {
  return a + b
}

An arrow function is the compact form. When the body is a single expression, the implicit return applies: no return keyword.

const addArrow = (a, b) => a + b
const shout = (s) => {
  const out = s.toUpperCase()
  return out + '!'
}

The trap: an arrow body that starts with { is read as a block, not an object literal. Wrap the object in parentheses.

const bad = () => { status: 'ok' } // a block; returns undefined
const good = () => ({ status: 'ok' }) // parens make it an object

Functions are values: callbacks and higher-order functions

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.

const twice = (fn, x) => fn(fn(x))
const inc = (n) => n + 1
twice(inc, 10) // 12
const ids = [1, 2, 3]
ids.map(inc) // [2, 3, 4] — the array method map, defined in the collections part

Closures: a function that remembers where it was born

function makeCounter() {
  let n = 0
  return function () {
    n += 1
    return n
  }
}

const c = makeCounter()
c() // 1
c() // 2

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.

Conditional expressions: ternary and &&

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.

const age = 20
const label = age >= 18 ? 'adult' : 'minor' // 'adult'
const logged = true
const note = logged && 'welcome back' // 'welcome back'
const off = false && 'never seen' // false

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'.

Early return as flow control

A guard clause checks the bad case first, returns immediately, and keeps the happy path flat instead of nested.

function price(ticket, age) {
  if (ticket === null) return 0
  if (age <= 12) return ticket * 0.5
  if (age >= 65) return ticket * 0.7
  return ticket
}

Each condition is a gate; reading top to bottom, the interesting line is never buried inside braces.

✅ Checkpoint — predict the output: coercion

Tip

Write down what each line produces before reading the answers.

Number('4.5')         // ?
'4' + 1               // ?
'4' * 2               // ?
parseInt('5px', 10)   // ?
(3.005).toFixed(2)    // ?
NaN + 1               // ?

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.

✅ Checkpoint — predict the output: the closure timer

Two counters built by one factory, with the calls interleaved. Predict each result.

Tip

function makeTimer(name) {
  let ticks = 0
  return function () {
    ticks += 1
    return name + ':' + ticks
  }
}

const a = makeTimer('a')
const b = makeTimer('b')
a() // ?
a() // ?
b() // ?
a() // ?

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.

📚 From Records to Collections: Objects, Arrays & the Immutability Discipline

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.

Object literals and shorthand

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:

const review_id = "DEMO_0001";
const rating = 5;

const r = { review_id: "DEMO_0001", rating: 5 };
const same = { review_id, rating };

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.

Dot vs bracket access

Once a record exists, its fields are reachable two ways:

const r = { review_id: "DEMO_0001", rating: 5 };

r.rating        // 5 — dot: the literal key name
r["rating"]     // 5 — bracket: the key name as a string

const key = "rating";
r[key]          // 5 — bracket only: the name is computed

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.

Keys are strings

Object keys are strings, even when they look like numbers; a numeric key is converted the moment it is stored:

const obj = {};
obj[1] = "first";

console.log(obj["1"]);   // "first" — the same slot, not a second one

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.

Copying an object: the spread

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:

const r = { review_id: "DEMO_0001", rating: 5 };

const copy = { ...r };
const edited = { ...r, rating: 4 };   // copy, then override one field

console.log(edited.rating);   // 4 — the copy carries the new value
console.log(r.rating);        // 5 — the original is untouched

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.

Our one dataset: six reviews, the canonical shape

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 same six records, uncleaned

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, map, filter: loop, transform, keep

forEach runs a side effect per element and returns undefined.

reviews.forEach((r) => console.log(r.rating));

map builds a new array by transforming every element.

const labels = reviews.map((r) => r.author + ": " + r.rating);

filter builds a new array with only the elements that pass a test.

const fiveStars = reviews.filter((r) => r.rating === 5);

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(): the comparator contract

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.

const byRating = (a, b) => a.rating - b.rating;   // order: 1, 2, 3, 4, 5, 5

Recency needs one line of recipe:

const byNewest = (a, b) => new Date(b.created_at) - new Date(a.created_at);

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.

sort() mutates — the trap

Two slides ago, forEach, map and filter never touched reviews. sort() does the opposite: it reorders the array in place.

const s = reviews.sort(byRating);
s === reviews;                     // true — one array, not two

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:

const newestFirst = reviews.slice().sort(byNewest);

slice() with no arguments is a fresh shallow copy; the mutation lands there.

The discipline: copy first, then change

[...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 source

The rule for this whole part: never sort or edit reviews — edit a copy.

The failure mode, told honestly

Silent damage, the alias.

const alias = reviews;                 // same array, second name
alias.sort(byRating);                  // sort through the alias
console.log(reviews.map(function (r) { return r.rating; }));

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.

reviews = reviews.filter(function (r) { return r.rating >= 3; });

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(): folding a list into an object accumulator

reduce walks a list carrying one value — the accumulator — to the end; here a plain object counting reviews per source.

const bySource = reviews.reduce(function (acc, r) {
  const key = r.source;
  if (!acc[key]) acc[key] = 0;   // explicit init — no magic defaults
  acc[key] = acc[key] + 1;
  return acc;
}, {});                          // the seed: an empty object
console.log(bySource);           // { Amazon: 2, BestBuy: 2, Walmart: 2 }

Forget return acc and the next step receives undefined.

for…of: the loop the backend lessons use

for...of walks the values of any iterable; today that means arrays — key/value iteration of objects is the next part.

for (const r of reviews) {
  const stars = '★'.repeat(r.rating);
  console.log(stars + ' ' + r.source);
}

Each step binds one full review object; prefer it over an index loop when you do not need the index.

🔎 Checkpoint — find the bug: the mutation that never undoes itself

Start from a fresh page so reviews holds ratings 5, 4, 1, 3, 2, 5, and write down three predictions before running.

function topRatedFirst(list) {
  return list.sort(function (a, b) { return b.rating - a.rating; });
}
console.log(reviews.map(function (r) { return r.rating; }));
const result = topRatedFirst(reviews);
console.log(reviews.map(function (r) { return r.rating; }));
console.log(result === reviews);

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, Defaults & Key-Value Tools

Destructuring: four shapes you will meet

Destructuring reads values out of an array or object in a single line. Four shapes cover everything in this session.

// (a) array pair: position decides
const [first, second] = list;

// (b) object by name: order does not matter
const { rating, source } = r;

// (c) rename while extracting
const { rating: stars } = r;

// (d) default inside the pattern (only when undefined)
const { author = "anonymous" } = r;

Destructuring the useState pair (a preview of Session 3)

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.

const [value, setValue] = useState(0)

This is React’s syntax arriving later in the course — recognition only. Nothing here needs to be writable yet; Session 3 owns it.

?? vs || — and ??=

This slide is the home of the ||-as-default idiom; the histogram slide that follows may use it freely.

const r = { rating: 0, source: "web" };

r.rating || 5          // 5  — wrong: 0 is falsy but legitimate
r.rating ?? 5          // 0  — ?? fires only for null / undefined

const settings = { theme: null };
settings.theme ??= "dark";   // assign only when still nullish

|| 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.

Dynamic keys: building a histogram

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.

const histogram = {};
for (const r of reviews) {
  histogram[r.source] = (histogram[r.source] || 0) + 1;
}

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.

for (const r of reviews) {
  histogram[r.source] ??= 0;   // seed only when the key is absent
  histogram[r.source] += 1;    // then accumulate
}

entries, fromEntries, and a first look at Map

Object.entries turns an object into an array of [key, value] pairs, Object.fromEntries turns such an array back into an object:

Object.entries(histogram);     // [["Amazon", 2], ["BestBuy", 2], ["Walmart", 2]]
Object.fromEntries(Object.entries(histogram));   // an equivalent object again

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.

?. optional chaining (three-line recognition)

const name = dirtyReviews[0]?.author?.name;
const label = dirtyReviews[0]?.author?.name ?? "anonymous";

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.

✅ Checkpoint — find the bug: the NaN histogram

The same reviews, a merged-too-fast loop, one console.log:

const broken = {};
for (const r of reviews) {
  broken[r.source] += 1;
}
console.log(broken["Amazon"]);

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:

broken[r.source] ??= 0;   // → Amazon 2 · BestBuy 2 · Walmart 2

🔎 Modules: How Files Find Each Other

Why a file needs import at all

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.

export: three forms

// rating.js
export default function renderRating(score) {   // what the file is for
  return '*'.repeat(score);
}

export function formatCount(n) {                // as many named as you need
  return n + ' reviews';
}

const threshold = 3;
export { threshold };                           // or export at the end

One default per file, any number of named exports. The default names the concern; the named ones are what other files may borrow.

import: three forms

// review-list.js - the same three targets, matched one by one
import renderRating from './rating.js';           // default
import { formatCount } from './rating.js';        // named
import * as utils from './rating.js';             // namespace

renderRating(5);
formatCount(12);
utils.threshold;

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.

The two rules that bite

Rule one. When the browser loads a module directly, without a bundler, the specifier is a URL, so it carries the extension.

import { formatCount } from './rating';      // ❌ fails
import { formatCount } from './rating.js';   // ✅ works

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.

{
  "type": "module"      // without this line Node assumes CommonJS
}

Then import inside a .js file throws SyntaxError: Cannot use import statement outside a module. Both mistakes stay invisible in the editor.

Plain script vs type=“module”

This session’s prototype loads as a plain script, just before </body>:

<script src="review-list.js"></script>

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:

<script type="module" src="review-list.js"></script>

CommonJS: recognize it, never write it

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.

Recognition only - do not write this
// rating.cjs - CommonJS, for reading old examples
const { threshold } = require('./rating');
module.exports = { threshold };

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.env.VITE_*

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.

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
const appName = import.meta.env.VITE_APP_NAME;

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.

📝 The DOM: Turning Data Into Pixels

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.

Finding a node

const list = document.getElementById("review-list")     // the <div> holding the cards
const filter = document.querySelector("#source-filter") // the <select>

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:

document.getElementById("reviewlist")   // hyphen dropped
// null — and the moment you use it: "Cannot read properties of null"

Making a node

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 vs innerHTML — and the consequence

textContent inserts text; innerHTML parses markup into nodes. With a hostile record, that difference is the whole story:

const hostile = { title: "<img src=x onerror=alert(1)>" }  // foreign data
heading.textContent = hostile.title   // inert: brackets show as characters
heading.innerHTML = hostile.title     // a real <img> is built, onerror runs

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.

✅ Checkpoint — verify the claim: “innerHTML += in the loop is fine”

Tip

An assistant proposes a shorter loop; predict what each pass does to cards already there:

for (const r of reviews) {
  list.innerHTML += "<div>" + r.title + "</div>"   // WRONG — two problems
}
  • += 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.
  • Pass k rebuilds k cards, so the work is quadratic in the review count.
  • The concatenation is the previous slide’s channel: 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.

Listening for the user

filter.addEventListener("change", (event) => {   // runs later, once per event
  console.log(event.target.value)                // the option just picked
})

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.

Reading what the user typed

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.

filter.addEventListener("change", (event) => {
  const chosen = event.target.value            // always a string
  const matches = reviews.filter((r) => r.source === chosen || chosen === "all")
  list.textContent = ""                        // clear the old cards
  // …then run the loop above over `matches`
})

.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.

Touch only nodes that exist

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:

document.addEventListener("DOMContentLoaded", () => {
  const list = document.getElementById("review-list")   // now never null
  // …the card loop from earlier
})

Where this goes next

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.

→ Async & Fetch: The Data Isn’t There Yet

The problem: the data isn’t there when your code runs

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.

1  you call fetch('./reviews.json')  → the request leaves, the call returns at once
2  your code keeps going             → logs, builds elements, returns
3  much later the bytes arrive       → "response ready" goes into the inbox
4  the lane is empty                 → the worker picks up the note, resumes you

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.

async function loadReviews() {
  const response = await fetch('./reviews.json')
  // response.json() returns a promise too: the body arrives after the headers (next slides)
  return await response.json()
}

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.

The ritual: fetch → check ok → throw → await json()

const response = await fetch('./reviews.json')
if (!response.ok) throw new Error(`HTTP ${response.status} for ${response.url}`)
const data = await response.json()

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.

const response = await fetch('./reviewz.json')   // one wrong letter in the name
const data = await response.json()
data.forEach(review => console.log(review.title))

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 →  2

The 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

const text = '[{"rating": 5}]'
JSON.parse(text)                   // sync: a string you already hold
const raw = await response.text()  // async: the body, as one string
await response.json()              // the last two lines, fused into one await

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.

Three shapes to recognize

.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.

✅ Checkpoint — predict the output: who logs first

Write the order down before you read on.

async function main() {
  console.log('1 before')
  const response = await fetch('./reviews.json')
  console.log('2 headers arrived')
  const data = await response.json()
  console.log('3 body parsed')
}
console.log('A about to call')
const pending = main()
console.log('B still in the lane')

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.

🏗 Putting It Together: The Vanilla Pattern

The whole page: load once, render on demand

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.

Load once, keep it in memory

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:

const sourceFilter = document.querySelector("#source-filter");
sourceFilter.addEventListener("change", () => renderReviews(event.target.value));

A change of source is a change of view, not of data; #sort-select is handled the same way, bound to change.

Filter, then sort, then render — the pipeline

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));
}
function buildCard(review) {
  const card = document.createElement("div");
  card.setAttribute("class", "card");
  const line = document.createElement("p");
  line.textContent = `${review.source} · ${review.rating}★ · ${review.body}`;
  card.appendChild(line);
  return card;
}

🔎 Checkpoint — find the three bugs in the assistant’s draft

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

  1. No response.ok check — the very defect the async checkpoint drilled, now hiding inside a bigger draft; the repetition is the point.
  2. json.data on a bare array — response.json() already hands you the array itself.
  3. 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).

Why this gets painful fast

  • Manual reconciliation. You decide by hand what to destroy and rebuild on every change.
  • Every new control is another listener plus another re-render call you write yourself.
  • State drifts. allReviews, the loading flag and what is on screen are separate facts nothing forces to agree.
  • Error paths multiply, because each entry point needs its own guard and its own message.

Tasks 2 to 4 of the practice file make you run this loop by hand, once per task.

React’s answer in one line: the UI is a function of state

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.

🚀 What You Can Now Read & Where It Continues

What you can now read

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.

  • ✅ a closure returning a function, and the binding the returned function keeps alive
  • ✅ [...list].filter().sort() as one pipeline, and why the copy comes first
  • ✅ count[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 object
  • ✅ const [rows] = await ... read as array destructuring that skips what you do not use
  • ✅ the fetch ritual: build the request, await it, check ok, only then read the body
  • ✅ import and export with an explicit .js specifier, and what the extension proves
  • ✅ event.target.value on a select, and why the result is a string and not a number

A ❌ on any line above is information, not a verdict: name the exact line that is still opaque before you move on.

Where this course continues

Three named destinations. Each one is now readable for a specific reason, not in general.

  • webdev_02_P_JavaScriptForReact.qmd — the practice session. You have just read Task 1; this is where you build it, run it and break it.
  • webdev_03_L_ReactFrontend.qmd — the 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.
  • webdev_04_L_NodeExpress.qmd — the aggregation loop is 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.

What lives in the optional lesson

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.

Key takeaways

Five sentences you should be able to defend in an exam, with the material closed.

  • Values in JavaScript are declared, not assumed: let and const say what may be rebound, and neither of them says anything about the type.
  • Coercion bites exactly where real data arrives — query strings, form fields, event.target.value — because digits inside a string are still a string.
  • Mutation is the trap: sort reorders in place, objects travel by reference, and [...list] is the cheapest defence you have.
  • The fetch ritual is non-negotiable: await hands you a response, not data, and an unchecked ok turns a 404 into a crash three lines later.
  • Read AI-generated output for shape before style: what is declared, what is returned, what is awaited, what is never checked.

The lecture ends here; the reading does not. Open the practice session before the next meeting and bring the lines that resisted you.