The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← CS 220 — Web Applications, SQL and Software Engineering

Weeks 3–5

JavaScript state, asynchronous requests and rendering

Learning objectives

  • Explain and trace the mechanisms in javascript state, asynchronous requests and rendering.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Current study directions: the original Academy lessons, preparation chapters, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters, source exercises and their historical assignment directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending. This current notice supersedes earlier textbook-supported study directions preserved below and in historical companion pages.

An interface is a state machine, even when written without a state-machine library. A request can be idle, loading, successful or failed; successful data can also be empty. Displaying unrelated content while a destination loads creates confusion because the user cannot distinguish navigation from an error. Render a destination-specific loading state and replace it with the requested content.

Promises represent work whose result is not yet available. await pauses the current asynchronous function, not the entire browser. A fetch promise can resolve for an HTTP error response, so inspect response.ok before interpreting the body as success. Handle malformed data separately from a failed connection. When two requests overlap, an earlier slower response can overwrite newer results. Use cancellation or a request identity check so the latest user intent wins.

When rendering untrusted text, use textContent or an escaping mechanism. Inserting external strings as HTML can turn data into executable markup. Keep state changes separate from visual effects where possible, making them easier to test. Define what happens when the user navigates away, presses twice or loses the connection. A spinner without a recoverable error state can leave the page indefinitely unusable.

Worked reasoning The incrementing identifier makes an older response ineligible to replace a newer request. HTTP errors and malformed arrays reach the error state. textContent avoids treating returned strings as markup. The example does not render individual orders or implement the API; it demonstrates the request-state boundary. A real retry button can call the function again.

Extended teaching and laboratory

A user can initiate request B while request A is still in flight. Network completion order need not match initiation order. Rendering whichever response arrives last can display stale state. Track the current request generation, and make success, error and loading transitions conditional on that generation. Cancellation can save work, but checking relevance is still useful because completion and cancellation can race.

Treat returned strings as data. textContent displays characters; inserting untrusted HTML can change document structure and introduce executable content in unsafe contexts. A valid JSON shape does not prove that an answer belongs to the currently selected customer.

Worked problem The user selects customer A, then B. B returns first with five orders; A returns later with two. Trace the correct UI state, including the old request’s error handler.

Step-by-step reasoning 1. Assign generation 1 to A and generation 2 to B. The current generation is 2.

  1. B can render five orders and clear its loading state because its generation is current.
  1. A’s success must not replace B’s list. Likewise, A’s later failure must not overwrite B’s success with an error.
  1. Verify the response object and render order descriptions as text. Keep selection identity, request identity and displayed data aligned.

Values, names and a deliberate input boundary

JavaScript executes statements that evaluate expressions, bind names and change state. A declaration `const rate = 1250` creates a binding that cannot later be reassigned; it does not make every object reachable through that binding immutable. `let hours = 2; const saved = rate * hours; hours = 3;` leaves saved at 2500 while a newly evaluated product is 3750. Assignment is an action at a moment, not a permanently recalculated equation. Prefer const when reassignment is unnecessary and let when it is part of the algorithm. Block-scoped bindings belong to their surrounding block; a function call also creates its own local execution context.

Numbers, strings, booleans, undefined and null have different roles. A form control's ordinary value is text even if it looks numeric. The expression `"12" + 3` produces text `"123"`, while `Number("12") + 3` produces 15. Conversion itself has semantics: `Number("")` produces zero, so an empty required value needs rejection before conversion. NaN is a numeric invalid-result value, not an exception automatically thrown by every failed conversion. A total can silently become NaN if validation is omitted. Use an explicit accepted notation, a conversion and the appropriate finite/safe-integer checks rather than hoping coercion chooses the intended units.

The following pure boundary accepts only a nonempty string of ASCII digits, with no sign, spaces or decimal point, and a value at most 1,000,000. It returns integer cents. Leading zeroes are permitted by this particular policy. This is a fictional teaching contract, not a currency system.

```javascript function readCents(text) { if (typeof text !== "string") throw new TypeError("Text required"); if (!/^[0-9]{1,7}$/.test(text)) throw new Error("Use 1–7 ASCII digits"); const cents = Number(text); if (!Number.isSafeInteger(cents) || cents > 1000000) { throw new Error("Amount is outside the accepted range"); } return cents; } ```

For `"0001250"`, lexical validation succeeds, conversion gives 1250 and the range check succeeds. Empty text and `"12.50"` fail before arithmetic; `"1000001"` passes the notation but fails the range. Distinguish a rejected spelling from an out-of-range value when explaining the boundary. JavaScript Number does not represent every integer of arbitrary magnitude exactly. For larger exact integer domains, choose a different representation such as BigInt or decimal text with appropriate algorithms and a serialization policy; do not merely increase this limit and assume exactness.

Use strict equality when the contract should not request conversion. `0 === "0"` is false. Truthiness is not a substitute for presence: zero can be a valid measured amount. An empty array is truthy even though its length is zero. Undefined often denotes a missing property or absent return; null can be an explicit absence value. Decide which absence values an interface accepts rather than merging all falsey values into one error. Logical `&&` and `||` short-circuit and return an operand; they are not restricted to producing booleans. A guard must precede an operation whose precondition it establishes.

Control flow, functions and retained state

An if/else chooses a branch according to its condition. A loop repeats a transition and needs both a maintained property and a progress argument. For a finite array of validated cents, initialize total to zero, add each element once and return after the loop. The invariant is that total equals the sum of the processed prefix. Returning inside the first iteration would compute the first value rather than the whole sum. Throwing on a bad value rejects the operation; returning zero after every error would invent a legitimate amount.

```javascript function totalCents(values) { if (!Array.isArray(values)) throw new TypeError("Array required"); let total = 0; for (const cents of values) { if (!Number.isSafeInteger(cents) || cents < 0) { throw new Error("Nonnegative safe integer cents required"); } const candidate = total + cents; if (!Number.isSafeInteger(candidate)) throw new Error("Total exceeds exact range"); total = candidate; } return total; } ```

For [1250,0,250], prefix totals are 1250,1250,1500. Empty input returns the additive identity zero; that result does not imply that any observations were supplied. The input array is not mutated. This implementation validates each amount and total but does not reuse readCents because its interface accepts numbers rather than text. Converting at a different layer is a deliberate boundary, not duplication to erase without thinking.

A function receives argument values and returns a result; reaching its end without a return yields undefined. A thrown exception transfers control to an applicable catch rather than supplying an ordinary return value. Arrow functions are convenient expressions, but an arrow body with braces still needs an explicit return to produce a computed result. `x => x * 2` returns the product, whereas `x => { x * 2; }` returns undefined. An ordinary function's `this` depends on how it is called; an arrow captures the surrounding this. Do not interchange them solely because their parameter lists look alike.

A closure retains access to lexical bindings. A counter factory that initializes count=0 and returns `() => ++count` gives each factory call its own retained count. Two calls of the first counter, one of a second and another of the first produce 1,2,1,3. Retained state can be useful for the request-generation policy in the original lesson; it can also cause unintended sharing if one global counter controls unrelated interface components. State ownership belongs in the design.

Collections are data contracts, not just syntax

Arrays hold ordered entries. Indexing begins at zero; reading a missing ordinary array entry yields undefined rather than proving that a value was present. push mutates the array; map produces a new array of transformed results. filter selects entries, and reduce accumulates a result under a stated initial value. Reducing an empty array without an initial value throws TypeError; an explicit initial total supplies the intended empty-input result. Mutating a collection while iterating it can change which entries are visited; prefer a clear transformation or specify the mutation behavior.

Objects associate property names with values. `{id:"A", cents:500}` bundles an event's fields, but neither the syntax nor a successful JSON parse validates the field types. Destructuring extracts values; it does not prove that the input supplied them. Object spread creates a new outer object while nested arrays/objects can remain shared. For `a={lines:[500]}; b={...a}; b.lines.push(700);`, both line properties refer to [500,700]. The outer objects differ, the nested list does not. Freeze and copying choices also require a precise depth/ownership policy.

Use Map when the desired interface is a key/value mapping with its own get/set/has operations; use Set when the specification requires unique values. A Set of amounts loses distinct equal-value events, just as the existing SQL DISTINCT example loses equal-priced line items. Group by the identity required by the question. To render two 500-cent orders, keep two order records and their stable IDs rather than deduplicating the numerical field. Object identity, value equality and business identity answer different questions.

The DOM is the live document interface

The browser exposes the document as nodes. A selector locates a node; the lookup can return null when no element matches. Attach behavior after the relevant markup exists, for example with a deferred external script. An event listener observes a named event and runs a callback when dispatched. Handle a form's submit event to cover keyboard submission as well as a mouse click. Call preventDefault only when the script actually owns an alternative submission path; otherwise the ordinary form behavior is useful.

```javascript const form = document.querySelector("#estimate"); const amount = document.querySelector("#amount"); const output = document.querySelector("#estimate-result"); if (form && amount && output) { form.addEventListener("submit", event => { event.preventDefault(); try { const cents = readCents(amount.value); output.textContent = `Estimate: ${cents} cents; not a saved order`; } catch (error) { output.textContent = "Enter whole nonnegative cents within the stated limit."; } }); } ```

This handler is a local estimate, so its text explicitly avoids a persistence claim. It assumes the markup supplies the named form/control/output and an accessible status/error strategy. The static markup and server validation remain necessary. If there is no script or the nodes do not exist, this callback does not run; a complete implementation must define the ordinary form fallback instead of hiding the form's purpose. Events can propagate through ancestor nodes; event delegation is useful for dynamically added entries, but the handler must verify which control initiated the action and which object it refers to.

Use textContent or createElement plus text nodes for untrusted descriptions. Constructing innerHTML from a visitor's text changes data into markup and can create an injection boundary. JSON.parse converts JSON syntax into values, while JSON.stringify creates a JSON representation; neither establishes ownership, permitted content or a complete application schema. BigInt, cyclic structures and absent values also need deliberate representation policies before serializing. Validate the response's structure and domain before using it as authoritative state.

Promise completion is not request authority

A Promise can be pending, fulfilled or rejected. then and catch register reactions; an async function returns a Promise, and await resumes that function after the awaited result is available. Other browser work can proceed while it waits. Synchronous work before the first await still runs immediately. Promise reactions do not make a CPU-bound loop nonblocking. Move heavy work or divide it appropriately when responsiveness matters.

Fetch fulfills with a Response for ordinary HTTP error statuses, so check response.ok or the specific status policy. Reading JSON is another asynchronous operation that can fail. A successful parse can still yield the wrong schema, and valid empty output is distinct from failure. The preserved original generation guard supplies the next obligation: only the currently relevant request may update either success or error state. Aborting an obsolete request can reduce work, but cancellation and completion can race, so relevance checks remain meaningful. A loading indicator is interface state; it must not block recovery indefinitely.

For two requests A then B, assign generations 1 and 2. If B returns an empty list, render a successful empty state for B. If A later rejects, its catch must not replace that view. If B's connection instead fails after a mutation request, distinguish unknown persistence from known rejection and reconcile using the stable operation ID. These cases connect the language mechanisms above to the original native request-race and retry teaching without replacing it.

Optional changed record and model

Trace `let count=2; const saved=count; count=3;`, the readCents inputs `"0001250"`, `""` and `"1000001"`, and totalCents([1250,0,250]). Next explain why `values.map(x => { x * 2; })` does not yield doubled numbers. Copy `{lines:[500]}` with object spread and append 700 through the copy. Finally let B return a valid empty array before A fails; identify which callback may alter the current view and what success text may claim.

**Model reasoning.** saved remains 2 while count becomes 3. The parser accepts 1250, rejects empty notation and rejects an out-of-range value respectively. The total is 1500, with zero still processed as a valid entry. The braced arrow never returns its multiplication result, so each mapped entry is undefined; add return or use the expression body. Object spread copies the outer property mapping, leaving both lines properties referring to the same nested array [500,700]. B's generation owns the view and displays a successful empty state. A's obsolete error is ignored. A local calculation may claim an estimate; a persisted-order message requires the actual server persistence contract and response. These are distinct errors in value flow, ownership and asynchronous authority, not one generic “JavaScript failed” diagnosis.

Use four equal rubric criteria: value/type/input trace; loop/function contract and failure behavior; collection/DOM ownership and safe rendering; and asynchronous state/relevance/persistence reasoning. Optional references remain the retained MDN JavaScript/DOM/Promise/Fetch sections. Original Academy teaching and fictional optional practice.

Apply the idea

The user selects customer A, then B. B returns first with five orders; A returns later with two. Trace the correct UI state, including the old request’s error handler.

B returns an empty list while A is still running. What should appear, and why should an empty array not be treated as a fetch failure?

Read the worked reasoning

Render a successful empty state for B, not A’s previous data and not a network error. An empty collection is a legitimate result under the API contract. Ignore A when it completes. Test empty, malformed, denied and failed responses separately so their distinct meanings remain visible.

Check understanding

Why check response.ok after fetch resolves?

  1. HTTP errors can still produce a resolved fetch response
    Feedback

    Transport completion and application success are different conditions.

  2. Resolution guarantees a 200 status
    Feedback

    A server can respond with an error status successfully over the network.

  3. JSON parsing verifies authorization
    Feedback

    Parsing a body does not establish access rights.

Further reading

Current study directions: the original Academy lessons, preparation chapters, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters, source exercises and their historical assignment directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending. This current notice supersedes earlier textbook-supported study directions preserved below and in historical companion pages.

Use the complete original preparation chapter, preserved investigation and optional changed-record reasoning for this unit. Earlier source directions remain in immutable edition 4.

My learning →