Small Group Tutorials

Here to help students catch up, keep up, and move ahead. Book a consultation here.

How to Master JavaScript fetch() in Punggol Tuition

Exterior view of Punggol Digital District in Singapore.

PUNGGOL TUITION · PRACTICAL MASTERY GUIDE

If a child says “the website is broken” whenever a fetch request fails, start with one concrete question: did the server reply with an HTTP status, did the network operation reject, or was the returned body impossible to decode? Those are three different problems and need three different fixes.

JavaScript fetch() returns a Promise for a Response. A normal 404 does not by itself make the promise reject; check response.ok or response.status. A 200 reply containing malformed JSON may pass that check but fail when response.json() parses it. Once learners can distinguish those three steps, debugging becomes a short, testable sequence instead of guesswork.

The chapters teach local browser and modern JavaScript response handling with fully invented family-project fixtures, explained outcomes and independent runnable checks. No real Punggol school, login service or tuition class is represented. Never use real student records or secrets in the demonstrations.

The worked records and names below are fictional. They are suggested family or learner exercises; they do not describe a particular Punggol school, a physical tuition premises, fees, guaranteed outcomes, or an advertised class timetable. The official technical source is MDN Web Docs: Using the Fetch API.

Find the right route

For a quick explanation, begin with the model and the first worked case. For a broken project, choose its closest chapter, predict the outcome, and follow the diagnostic route. For practice, complete one contrasting example before consulting the worked answer. The full index is expandable so the long guide remains navigable on a phone.

The wider family-study context is in How Studying Works; local learning resources can be explored through the Punggol education and town-life index.

Route 1: chapter 1 to chapter 4 — Understand HTTP, Promise and JSON outcomes.

Route 2: chapter 5 to chapter 8 — Read body streams and validate representation.

Route 3: chapter 9 to chapter 12 — Build deliberate requests and cancellation.

Route 4: chapter 13 to chapter 16 — Handle concurrency, retries and redirects.

Route 5: chapter 17 to chapter 20 — Apply browser security and honest UI reporting.

Open all twenty chapter headings
  1. 1. Distinguish network resolution from HTTP status
  2. 2. Check the precise meaning of response.ok
  3. 3. Catch a broken JSON representation
  4. 4. Handle responses with no content
  5. 5. Read a response body only once
  6. 6. Clone before two intentional reads
  7. 7. Choose text rather than JSON when promised
  8. 8. Inspect Content-Type without trusting it blindly
  9. 9. Encode search queries with URLSearchParams
  10. 10. Build JSON POST requests deliberately
  11. 11. Understand HTTP headers and credentials separately
  12. 12. Cancel a stale request with AbortController
  13. 13. Prevent older responses overwriting newer choices
  14. 14. Handle Promise.all failure explicitly
  15. 15. Retry cautiously and distinguish GET from POST
  16. 16. Read Retry-After as advisory response metadata
  17. 17. Interpret redirects before reading data
  18. 18. Understand cache options without inventing performance results
  19. 19. Treat CORS and opaque responses as browser-enforced boundaries
  20. 20. Design UI states that preserve evidence

Start here: the original compact lesson

The following foundation is preserved and developed from the earlier checkpoint for this exact article. Work through it once; the extensive practice chapters below turn its principles into verifiable decisions. If a snippet refers to a local demonstration server or invented records, treat that environment as hypothetical until you set it up yourself.

A webpage can contact a server and receive an answer, but an answer is not necessarily a success. That is the central puzzle behind JavaScript’s fetch() API. A student may write const response = await fetch(url); and assume the data are now safe to display. Yet the server may return a 404 response for a missing resource, a 500 response for an error, or a perfectly valid response containing text rather than JSON. A parent helping with a simple school coding project should ask: What did the browser actually receive, and which part of the response have we checked?

By the second step of this lesson, the student should know the essential distinction: fetch() normally fulfils its promise with a Response object when the HTTP exchange completes, even for HTTP error responses such as 404. A failed network request can reject the promise. Consequently, a correct client checks response.ok or response.status before treating the HTTP result as successful. It then reads the response body using a suitable method such as response.json(), understanding that parsing itself can fail. One promise, one HTTP status and one body parser can fail for different reasons.

The exercises use a local fictional project application with invented items. They do not involve real pupils’ data, a school API, actual Punggol institutions or a physical eduKate tuition branch. A learner should develop against a local test server or deterministic mocks, never against a production system without permission.

1. The three stages of a successful request

A reliable mental model separates the transport, HTTP result and data format. First, can the client reach the endpoint? If a DNS lookup fails or a network connection cannot be established, fetch may reject. Second, did the server report success? A reachable server can return a 404 or 500 with an ordinary Response; response.ok is false outside the successful 200–299 range. Third, can the body be interpreted in the expected format? A successful 200 response containing broken JSON can still cause response.json() to reject with a parsing error.

A useful example is a hypothetical endpoint at http://localhost:3000/activities. The path exists only if the learner has started a local practice server that provides it. Do not present it as an active public website. The following is a pattern to study, not a claim that the endpoint is available to readers:

async function loadActivities() {
  const response = await fetch('http://localhost:3000/activities');
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  return await response.json();
}

This function first waits for an HTTP response, then checks status, then parses JSON. A caller still needs to catch the thrown error and decide what helpful message to display. The user-facing message should not claim “No activities exist” for a network outage or a malformed server response. Those are different situations.

2. A 404 is not the same as a rejected fetch promise

Imagine a request for a fictional homework resource at /activity/9999 where the server responds with 404 Not Found. The browser may successfully exchange HTTP messages; the promise therefore fulfils with a Response, whose status is 404 and whose .ok property is false. The program should not rely on catch alone to detect this condition, because a catch block is entered on rejection or explicit throwing, not merely because an HTTP status expresses failure.

try {
  const response = await fetch('/activity/9999');
  if (!response.ok) {
    console.log('Server returned', response.status);
  } else {
    console.log(await response.json());
  }
} catch (error) {
  console.log('Request or processing failed', error);
}

This deliberately prints status information without trying to parse a nonexistent resource as if it were successful. However, the console is not a complete user interface. A real application should explain that the requested item was not found, distinguish it from connectivity problems and give the user a safe retry or navigation route where appropriate.

A useful diagnostic uses new Response('Missing', {status:404}) in a runtime that supports the Response constructor. The student can check response.status === 404, response.ok === false and await response.text() === 'Missing' without contacting any server. This proves an HTTP error response is still a response object. It does not simulate every aspect of network failure, and students should say so.

3. Status is part of the protocol, not an interpretation of the body

The HTTP status and response body are separate pieces of evidence. A 200 response could contain an error message formatted as JSON because the server’s application contract is unusual; a 404 response could contain a helpful HTML page. The client should follow the actual protocol and application specification, not treat the text of a body as a replacement for response.ok.

A practice exercise asks the student to compare three mock responses: a 200 body {"items":[1,2]}, a 404 body {"error":"not found"}, and a 200 body not valid JSON. Which operations succeed? The first passes the status check and JSON parse. The second fails the status check unless the application explicitly handles that status as an expected outcome. The third passes the HTTP check but fails JSON parsing. The correct answer names the failing stage rather than saying all three are “fetch errors.”

4. Reading a body consumes a stream

A Response body is a stream. After a body-reading method such as response.json() or response.text() has successfully consumed it, the same body generally cannot be read again. Students sometimes log await response.text() for debugging and then call await response.json() on the same response, expecting both to work. That can fail because the body has been disturbed or consumed.

For an ordinary JSON endpoint, parse once and keep the parsed object:

const response = await fetch('/activities');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
console.log(data);

A developer who genuinely needs separate reads can investigate response.clone() before consumption, recognising that cloning involves stream mechanics and potential buffering costs. Do not teach cloning as a default habit for simple classroom projects. The better debugging question is usually, “Which format did we expect, and why are we trying to parse it twice?”

5. Not every response contains JSON

A successful endpoint might return plain text, an image, a blob or no content. Reading response.json() unconditionally is as careless as parsing every school worksheet as a table. The client should know what representation the server promises. A JSON API should normally advertise an appropriate Content-Type, but headers alone cannot guarantee that the body is well formed or trustworthy.

In a hypothetical plain-text endpoint:

const response = await fetch('/notice.txt');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const notice = await response.text();

A report that merely echoes text should avoid inserting it into HTML as trusted markup. Safe rendering depends on the application environment; user-controlled content should generally be assigned as text rather than interpreted as script-bearing HTML. This is not only a security issue. It is also a literacy lesson: data and instructions have different roles even when both appear as strings.

6. Query parameters should be encoded

A student may want to look up a fictional activity by name, such as Science & Art. Concatenating it directly into a URL risks misinterpreting characters such as &, ? and spaces. The modern URL and URLSearchParams interfaces can build the query safely and make parameter names explicit.

const url = new URL('/activities', window.location.origin);
url.searchParams.set('topic', 'Science & Art');
const response = await fetch(url);

This example assumes a browser environment with an origin. It does not promise that every URL or external service can be fetched from every webpage; CORS and permissions still apply. A useful test changes the topic to A+B and asks whether the server should receive a literal plus sign, a space or a string of separate parameters. Use the URL object’s serialised query to inspect the encoding before sending any request.

7. POST requests change the responsibilities

Retrieving a public list with GET is different from sending data with POST. In a fictional local project, an authorised client may submit a new activity record. The request must explain its method, format and intended body:

const response = await fetch('/activities', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({topic: 'Science', minutes: 20})
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);

This is not permission to submit records to any real server. Use a local mock endpoint that the learner controls. Check whether the server expects JSON; not all APIs do. Consider accidental double submissions when a student clicks twice or retries after a timeout. The server must define how it handles such duplicate requests, because the client cannot guarantee exactly-once processing merely by placing await before fetch.

8. Timeouts and cancellation are deliberate application choices

The Fetch API supports request cancellation via AbortController and the signal option. A user may navigate away from a page or choose to cancel a long operation. A controlled cancellation can be distinguished from a random network error by inspecting the error and the signal state, while being careful about variations across runtimes.

const controller = new AbortController();
const responsePromise = fetch('/activities', {signal: controller.signal});
// In a real application, a user action may call controller.abort().
const response = await responsePromise;

Do not present this snippet as a fully implemented timeout. It merely passes a signal and explains that a later action could cancel the request. If adding a timed abort, clean up any timeout resource appropriately and decide what message to show. A cancelled operation should not be described as a server returning zero records. That would change an operational status into a false factual claim.

An advanced exercise asks the learner to stop a previous search when a new search begins. The goal is to prevent stale results overwriting more recent user choices. Cancellation helps manage resources, but the application should also guard its state transitions. This is a distinct reader job from displaying a spinner.

9. CORS is not a promise-rejection repair technique

Browsers apply cross-origin policies to protect users. An endpoint can exist and work when tested directly in a separate tool but still be unavailable to a script loaded from another origin because the server has not authorised that cross-origin access. Adding mode:'no-cors' is not a magic way to read protected results; it commonly produces an opaque response whose status and body cannot be read as the student intended.

The appropriate diagnosis asks who controls the server, which origin is making the request, whether the endpoint is intended for browser clients and which response headers the server sends. Do not instruct learners to bypass school networks, authentication, browser safeguards or server policies. For a home exercise, a same-origin local test endpoint is a simpler and safer place to begin.

10. Retry is not always safe

When a GET request fails transiently, a carefully limited retry may be reasonable. When a POST request has possibly succeeded but its response was lost, retrying blindly can create duplicate records. A server may offer an idempotency mechanism, or the application may need to read back by a stable request identifier. This distinction matters in real project workflows and explains why network programming cannot be taught as “if it fails, try again.”

For an invented event-registration application, suppose a POST reaches the server and creates record 42, but the network drops the response. The client sees an error and has no confirmation. A second POST might create record 43 with the same information unless the server deduplicates it. The responsible behaviour is to check the application’s documented retry and readback procedure. That is a practical form of evidence-aware computing.

11. Handle UI states separately from protocol states

A client can display a loading indicator, successful data, empty results, an application error, a network error or a cancelled state. Those are distinct presentation choices. Empty data after a successful request are not the same as a missing resource. A 404 is not necessarily an instruction to retry. A JSON parse error is not evidence that the server is unreachable. Encourage the learner to draw a simple state diagram before writing rendering code.

The diagram might have states idle, loading, success, empty, http-error, network-error, format-error, and cancelled, with only transitions that the application can actually identify. Not every interface needs all eight. The goal is to prevent vague error handlers from hiding what the program has learned about the failure.

12. A reliable test bench without real network access

A beginner can test much of the response-handling code with the Response constructor without making a real request. For example:

async function readJson(response) {
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

const good = new Response('{"count": 3}', {
  status: 200,
  headers: {'Content-Type': 'application/json'}
});
console.log(await readJson(good));

The expected object has a count property equal to three. A second test constructs a 404 response with a body. That test should throw HTTP 404 before parsing. A third test uses status 200 with body broken and should fail during JSON parsing. Each test isolates one contract. After those three work, a learner can add a local mock server to test actual network behaviour.

The parent can help with this process by asking: “What did we change between tests, and which layer were we trying to test?” If several aspects change at once, debugging becomes guesswork. The skill transfers to science experiments, spreadsheet audits and mathematical proofs: vary one assumption when possible, and explain the observation.

Initial practice bank with explained answers

Question 1. Does fetch() reject on every 404? No. Ordinary HTTP error statuses still return a Response object; the application must inspect response.ok or response.status.

Question 2. What does response.ok mean? It is true for successful HTTP status codes in the 200–299 range, not a guarantee that the JSON format or business content is correct.

Question 3. What happens when a 200 response contains invalid JSON? The HTTP status check can pass, but response.json() rejects because parsing fails.

Question 4. Why might two sequential body reads fail? A response body’s stream is generally consumed by the first reading operation, so the second cannot simply reread it.

Question 5. Why use URLSearchParams? It makes query names and values explicit and handles the encoding of special characters.

Question 6. Why does no-cors not solve an API permission problem? It does not grant scripts the ability to read otherwise disallowed cross-origin response data.

Question 7. Can a failed POST response prove the server did not create the record? No. The server may have processed the request before communication failed. Use the server’s documented readback or idempotency mechanism.

Question 8. Is no result the same as server error? No. A successful request can legitimately return an empty collection. The UI should represent the distinction.

Question 9. When is AbortController useful? When an application needs to cancel a request, for instance because a user leaves the page or starts a newer search. It does not replace handling other failure modes.

Question 10. Why test with fixed responses before connecting a live endpoint? Deterministic tests isolate HTTP status and parsing logic, so the learner can reason about each layer without unreliable network conditions.

The authoritative guide is MDN’s Using the Fetch API, with related specification references linked from that documentation. The local activities are proposed practice exercises, not advertised services. How Studying Works is an existing eduKatePunggol resource about learning habits.

CHAPTER 1 OF 20 · Back to contents

1. Distinguish network resolution from HTTP status

Start with the answer: A returned HTTP 404 still fulfils an ordinary fetch promise with a Response; inspect status or ok before accepting the result.

The promise answers whether a usable Response was obtained, while ok judges the HTTP result. A server-side error page is not the same failure as a disconnected client.

Common tempting error: Putting every unsuccessful page into a catch block and pretending the status was inaccessible.

Diagnostic for a parent or project partner: If a server really answered 404, which object contains that evidence?

Lab 1: distinguish network resolution from http status — a family revision tracker

For a fictional family a family revision tracker, the response is delayed but arrives intact. The topic is ‘Science & Art’ and the controlled fixture uses count 2. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a returned http 404 still fulfils an ordinary fetch promise with a response; inspect status or ok before accepting the result.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=2;
const topic="Science & Art";
const r=new Response('reply',{status:200}); const result={status:r.status,ok:r.ok,kind:r.ok?'accepted':'http-error'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For distinguish network resolution from http status in a family revision tracker, with the hypothetical ‘Science & Art’ topic and count 2, the independently executed Node.js Web API test prints {“status”:200,”ok”:true,”kind”:”accepted”}. Its observable properties are specific: A synthetic HTTP 200 reply fulfils the Response path; the status check classifies it as acceptable. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For distinguish network resolution from http status in a family revision tracker, start with the code expression responsible for the result: A fetch promise would reject for a transport or permission problem, not merely because the returned status displeased an application. The controlled topic is ‘Science & Art’ and the mock count is 2. The promise answers whether a usable Response was obtained, while ok judges the HTTP result. A server-side error page is not the same failure as a disconnected client. In this case the returned keys [‘status’, ‘ok’, ‘kind’] are the evidence to inspect, not a claim that a real website is available. Start by identifying the unit of observation, then apply only the rule relevant to that unit..

Check the boundary. First substitute topic “Art & Coding” for ‘Science & Art’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this distinguish network resolution from http status case in a family revision tracker, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Try this on a small, invented table before using any real schoolwork. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: distinguish network resolution from http status — a small library-book experiment

A pupil builds a little a small library-book experiment and wants to understand distinguish network resolution from http status. With topic ‘Math + sketches’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a returned http 404 still fulfils an ordinary fetch promise with a response; inspect status or ok before accepting the result.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=11;
const topic="Math + sketches";
const r=new Response('reply',{status:404}); const result={status:r.status,ok:r.ok,kind:r.ok?'accepted':'http-error'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For distinguish network resolution from http status in a small library-book experiment, with the hypothetical ‘Math + sketches’ topic and count 11, the independently executed Node.js Web API test prints {“status”:404,”ok”:false,”kind”:”http-error”}. Its observable properties are specific: A synthetic HTTP 404 reply fulfils the Response path; the status check classifies it as HTTP failure. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For distinguish network resolution from http status in a small library-book experiment, start with the code expression responsible for the result: A fetch promise would reject for a transport or permission problem, not merely because the returned status displeased an application. The controlled topic is ‘Math + sketches’ and the mock count is 11. The promise answers whether a usable Response was obtained, while ok judges the HTTP result. A server-side error page is not the same failure as a disconnected client. In this case the returned keys [‘status’, ‘ok’, ‘kind’] are the evidence to inspect, not a claim that a real website is available. Check the case that would make a tempting shortcut wrong..

Check the boundary. Now replace the invented count 11 with 16, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this distinguish network resolution from http status case in a small library-book experiment, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. No real pupil information is needed; the test data are deliberately imaginary. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: distinguish network resolution from http status — an after-CCA practice planner

The make-believe records for an after-CCA practice planner contain 6 observations under topic ‘Math + sketches’. A friend says the program has worked because the console displays something. Test distinguish network resolution from http status: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a returned http 404 still fulfils an ordinary fetch promise with a response; inspect status or ok before accepting the result.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=6;
const topic="Math + sketches";
const r=new Response('reply',{status:500}); const result={status:r.status,ok:r.ok,kind:r.ok?'accepted':'http-error'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For distinguish network resolution from http status in an after-CCA practice planner, with the hypothetical ‘Math + sketches’ topic and count 6, the independently executed Node.js Web API test prints {“status”:500,”ok”:false,”kind”:”http-error”}. Its observable properties are specific: A synthetic HTTP 500 reply fulfils the Response path; the status check classifies it as HTTP failure. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For distinguish network resolution from http status in an after-CCA practice planner, start with the code expression responsible for the result: A fetch promise would reject for a transport or permission problem, not merely because the returned status displeased an application. The controlled topic is ‘Math + sketches’ and the mock count is 6. The promise answers whether a usable Response was obtained, while ok judges the HTTP result. A server-side error page is not the same failure as a disconnected client. In this case the returned keys [‘status’, ‘ok’, ‘kind’] are the evidence to inspect, not a claim that a real website is available. Cross-check with an independent hand calculation using the smallest workable values..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For an after-CCA practice planner, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this distinguish network resolution from http status case in an after-CCA practice planner, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Independent checking beats a polished screen that nobody can explain. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: distinguish network resolution from http status — a school-holiday project notebook

After a shared family activity around a school-holiday project notebook, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Coastal habitats?’ and the invented integer 15. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a returned http 404 still fulfils an ordinary fetch promise with a response; inspect status or ok before accepting the result.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=15;
const topic="Coastal habitats?";
const r=new Response('reply',{status:201}); const result={status:r.status,ok:r.ok,kind:r.ok?'accepted':'http-error'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For distinguish network resolution from http status in a school-holiday project notebook, with the hypothetical ‘Coastal habitats?’ topic and count 15, the independently executed Node.js Web API test prints {“status”:201,”ok”:true,”kind”:”accepted”}. Its observable properties are specific: A synthetic HTTP 201 reply fulfils the Response path; the status check classifies it as acceptable. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For distinguish network resolution from http status in a school-holiday project notebook, start with the code expression responsible for the result: A fetch promise would reject for a transport or permission problem, not merely because the returned status displeased an application. The controlled topic is ‘Coastal habitats?’ and the mock count is 15. The promise answers whether a usable Response was obtained, while ok judges the HTTP result. A server-side error page is not the same failure as a disconnected client. In this case the returned keys [‘status’, ‘ok’, ‘kind’] are the evidence to inspect, not a claim that a real website is available. Write down the unsuccessful interpretation and explain why it fails..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “putting every unsuccessful page into a catch block and pretending the status was inaccessible.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this distinguish network resolution from http status case in a school-holiday project notebook, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Save the example so the learner can rerun it with a fresh number next week. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe distinguish network resolution from http status in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Draw two paths: rejected promise and fulfilled response with an unacceptable HTTP status. Try this on a small, invented table before using any real schoolwork.

CHAPTER 2 OF 20 · Back to contents

2. Check the precise meaning of response.ok

Start with the answer: The ok property is true for status 200 through 299, not for every status that a real application might recognise.

A successful HTTP request does not by itself guarantee useful data, and a non-2xx response can still carry information the user interface should handle.

Common tempting error: Equating 304, 404, 429 or 500 with a success payload without explaining protocol expectations.

Diagnostic for a parent or project partner: What status range does ok implement and what policy does the particular app need?

Lab 1: check the precise meaning of response.ok — a small library-book experiment

For a fictional family a small library-book experiment, the response is delayed but arrives intact. The topic is ‘Punggol eco-notes’ and the controlled fixture uses count 9. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is the ok property is true for status 200 through 299, not for every status that a real application might recognise.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=9;
const topic="Punggol eco-notes";
const r=new Response('',{status:400}); const result={status:r.status,ok:r.ok,classification:r.ok?'2xx':'not-2xx'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For check the precise meaning of response.ok in a small library-book experiment, with the hypothetical ‘Punggol eco-notes’ topic and count 9, the independently executed Node.js Web API test prints {“status”:400,”ok”:false,”classification”:”not-2xx”}. Its observable properties are specific: The tested 400 sits outside the 200–299 interval. A 304 may be meaningful during cache processing but it is not response.ok. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For check the precise meaning of response.ok in a small library-book experiment, start with the code expression responsible for the result: A protocol property and an application-specific recovery policy answer different questions. The controlled topic is ‘Punggol eco-notes’ and the mock count is 9. A successful HTTP request does not by itself guarantee useful data, and a non-2xx response can still carry information the user interface should handle. In this case the returned keys [‘status’, ‘ok’, ‘classification’] are the evidence to inspect, not a claim that a real website is available. Draw a miniature table and count the rows before calculating any summary..

Check the boundary. First substitute topic “Art & Coding” for ‘Punggol eco-notes’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this check the precise meaning of response.ok case in a small library-book experiment, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A Punggol family can practise this with fictional numbers after dinner or over a weekend. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: check the precise meaning of response.ok — a fictional student coding challenge

A pupil builds a little a fictional student coding challenge and wants to understand check the precise meaning of response.ok. With topic ‘Science & Art’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is the ok property is true for status 200 through 299, not for every status that a real application might recognise.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=18;
const topic="Science & Art";
const r=new Response('',{status:200}); const result={status:r.status,ok:r.ok,classification:r.ok?'2xx':'not-2xx'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For check the precise meaning of response.ok in a fictional student coding challenge, with the hypothetical ‘Science & Art’ topic and count 18, the independently executed Node.js Web API test prints {“status”:200,”ok”:true,”classification”:”2xx”}. Its observable properties are specific: The tested 200 sits inside the 200–299 interval. A 304 may be meaningful during cache processing but it is not response.ok. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For check the precise meaning of response.ok in a fictional student coding challenge, start with the code expression responsible for the result: A protocol property and an application-specific recovery policy answer different questions. The controlled topic is ‘Science & Art’ and the mock count is 18. A successful HTTP request does not by itself guarantee useful data, and a non-2xx response can still carry information the user interface should handle. In this case the returned keys [‘status’, ‘ok’, ‘classification’] are the evidence to inspect, not a claim that a real website is available. Compare the desired answer with an alternative that looks similar but measures something else..

Check the boundary. Now replace the invented count 18 with 23, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this check the precise meaning of response.ok case in a fictional student coding challenge, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The goal is not to finish a huge worksheet; it is to explain one reliable decision. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: check the precise meaning of response.ok — a school-holiday project notebook

The make-believe records for a school-holiday project notebook contain 13 observations under topic ‘Science & Art’. A friend says the program has worked because the console displays something. Test check the precise meaning of response.ok: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is the ok property is true for status 200 through 299, not for every status that a real application might recognise.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=13;
const topic="Science & Art";
const r=new Response('',{status:299}); const result={status:r.status,ok:r.ok,classification:r.ok?'2xx':'not-2xx'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For check the precise meaning of response.ok in a school-holiday project notebook, with the hypothetical ‘Science & Art’ topic and count 13, the independently executed Node.js Web API test prints {“status”:299,”ok”:true,”classification”:”2xx”}. Its observable properties are specific: The tested 299 sits inside the 200–299 interval. A 304 may be meaningful during cache processing but it is not response.ok. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For check the precise meaning of response.ok in a school-holiday project notebook, start with the code expression responsible for the result: A protocol property and an application-specific recovery policy answer different questions. The controlled topic is ‘Science & Art’ and the mock count is 13. A successful HTTP request does not by itself guarantee useful data, and a non-2xx response can still carry information the user interface should handle. In this case the returned keys [‘status’, ‘ok’, ‘classification’] are the evidence to inspect, not a claim that a real website is available. Predict the behaviour before running a test; the difference between prediction and result is the learning target..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a school-holiday project notebook, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this check the precise meaning of response.ok case in a school-holiday project notebook, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Treat a version-dependent result as a prompt to consult the current official manual. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: check the precise meaning of response.ok — a made-up quiz analysis

After a shared family activity around a made-up quiz analysis, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Math + sketches’ and the invented integer 5. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is the ok property is true for status 200 through 299, not for every status that a real application might recognise.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=5;
const topic="Math + sketches";
const r=new Response(null,{status:304}); const result={status:r.status,ok:r.ok,classification:r.ok?'2xx':'not-2xx'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For check the precise meaning of response.ok in a made-up quiz analysis, with the hypothetical ‘Math + sketches’ topic and count 5, the independently executed Node.js Web API test prints {“status”:304,”ok”:false,”classification”:”not-2xx”}. Its observable properties are specific: The tested 304 sits outside the 200–299 interval. A 304 may be meaningful during cache processing but it is not response.ok. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For check the precise meaning of response.ok in a made-up quiz analysis, start with the code expression responsible for the result: A protocol property and an application-specific recovery policy answer different questions. The controlled topic is ‘Math + sketches’ and the mock count is 5. A successful HTTP request does not by itself guarantee useful data, and a non-2xx response can still carry information the user interface should handle. In this case the returned keys [‘status’, ‘ok’, ‘classification’] are the evidence to inspect, not a claim that a real website is available. Carry the result back to the family’s original decision, without claiming more than the data support..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “equating 304, 404, 429 or 500 with a success payload without explaining protocol expectations.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this check the precise meaning of response.ok case in a made-up quiz analysis, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Try this on a small, invented table before using any real schoolwork. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe check the precise meaning of response.ok in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Predict each status before testing it; separate a protocol fact from a business decision. This is a proposed home exercise rather than a service or school claim.

CHAPTER 3 OF 20 · Back to contents

3. Catch a broken JSON representation

Start with the answer: A response may pass the HTTP check yet reject at response.json() because the body is not valid JSON.

A loader has at least two contracts: receiving an acceptable HTTP response and decoding the advertised content. Different failures deserve different diagnoses.

Common tempting error: Saying the network is broken when the server sent a successful status with malformed JSON.

Diagnostic for a parent or project partner: Did the error occur while receiving the response or decoding its body?

Lab 1: catch a broken json representation — a fictional student coding challenge

For a fictional family a fictional student coding challenge, the response is delayed but arrives intact. The topic is ‘Coastal habitats?’ and the controlled fixture uses count 16. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a response may pass the http check yet reject at response.json() because the body is not valid json.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=16;
const topic="Coastal habitats?";
const r=new Response("{\"visits\":3}",{status:200,headers:{'Content-Type':'application/json'}}); let result; try { const data=await r.json(); result={stage:'parsed',data}; }catch(e){result={stage:'format-error',errorName:e.name};}
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For catch a broken json representation in a fictional student coding challenge, with the hypothetical ‘Coastal habitats?’ topic and count 16, the independently executed Node.js Web API test prints {“stage”:”parsed”,”data”:{“visits”:3}}. Its observable properties are specific: The response has a successful HTTP status, but the JSON parser makes a separate decision about the body grammar. An empty response body is not the same as a JSON empty array. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For catch a broken json representation in a fictional student coding challenge, start with the code expression responsible for the result: Use an explicit 204 branch for a genuinely bodyless successful endpoint rather than hiding its meaning in a parsing catch. The controlled topic is ‘Coastal habitats?’ and the mock count is 16. A loader has at least two contracts: receiving an acceptable HTTP response and decoding the advertised content. Different failures deserve different diagnoses. In this case the returned keys [‘stage’, ‘data’] are the evidence to inspect, not a claim that a real website is available. Explain the result in ordinary language before trusting a convenient display..

Check the boundary. First substitute topic “Art & Coding” for ‘Coastal habitats?’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this catch a broken json representation case in a fictional student coding challenge, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A useful parent prompt is to request a prediction, not a memorised command. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: catch a broken json representation — a mock group presentation tracker

A pupil builds a little a mock group presentation tracker and wants to understand catch a broken json representation. With topic ‘Punggol eco-notes’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a response may pass the http check yet reject at response.json() because the body is not valid json.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=8;
const topic="Punggol eco-notes";
const r=new Response("{visits:3}",{status:200,headers:{'Content-Type':'application/json'}}); let result; try { const data=await r.json(); result={stage:'parsed',data}; }catch(e){result={stage:'format-error',errorName:e.name};}
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For catch a broken json representation in a mock group presentation tracker, with the hypothetical ‘Punggol eco-notes’ topic and count 8, the independently executed Node.js Web API test prints {“stage”:”format-error”,”errorName”:”SyntaxError”}. Its observable properties are specific: The response has a successful HTTP status, but the JSON parser makes a separate decision about the body grammar. An empty response body is not the same as a JSON empty array. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For catch a broken json representation in a mock group presentation tracker, start with the code expression responsible for the result: Use an explicit 204 branch for a genuinely bodyless successful endpoint rather than hiding its meaning in a parsing catch. The controlled topic is ‘Punggol eco-notes’ and the mock count is 8. A loader has at least two contracts: receiving an acceptable HTTP response and decoding the advertised content. Different failures deserve different diagnoses. In this case the returned keys [‘stage’, ‘errorName’] are the evidence to inspect, not a claim that a real website is available. Keep the input unchanged while adjusting a single condition..

Check the boundary. Now replace the invented count 8 with 13, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this catch a broken json representation case in a mock group presentation tracker, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Independent checking beats a polished screen that nobody can explain. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: catch a broken json representation — a made-up quiz analysis

The make-believe records for a made-up quiz analysis contain 3 observations under topic ‘Punggol eco-notes’. A friend says the program has worked because the console displays something. Test catch a broken json representation: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a response may pass the http check yet reject at response.json() because the body is not valid json.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=3;
const topic="Punggol eco-notes";
const r=new Response("[]",{status:200,headers:{'Content-Type':'application/json'}}); let result; try { const data=await r.json(); result={stage:'parsed',data}; }catch(e){result={stage:'format-error',errorName:e.name};}
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For catch a broken json representation in a made-up quiz analysis, with the hypothetical ‘Punggol eco-notes’ topic and count 3, the independently executed Node.js Web API test prints {“stage”:”parsed”,”data”:[]}. Its observable properties are specific: The response has a successful HTTP status, but the JSON parser makes a separate decision about the body grammar. An empty response body is not the same as a JSON empty array. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For catch a broken json representation in a made-up quiz analysis, start with the code expression responsible for the result: Use an explicit 204 branch for a genuinely bodyless successful endpoint rather than hiding its meaning in a parsing catch. The controlled topic is ‘Punggol eco-notes’ and the mock count is 3. A loader has at least two contracts: receiving an acceptable HTTP response and decoding the advertised content. Different failures deserve different diagnoses. In this case the returned keys [‘stage’, ‘data’] are the evidence to inspect, not a claim that a real website is available. Ask whether the structure remains valid when the number of records doubles..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a made-up quiz analysis, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this catch a broken json representation case in a made-up quiz analysis, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A clear explanation is more valuable than guessing an answer from the display. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: catch a broken json representation — a weather-observation practice sheet

After a shared family activity around a weather-observation practice sheet, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Science & Art’ and the invented integer 12. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a response may pass the http check yet reject at response.json() because the body is not valid json.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=12;
const topic="Science & Art";
const r=new Response("",{status:200,headers:{'Content-Type':'application/json'}}); let result; try { const data=await r.json(); result={stage:'parsed',data}; }catch(e){result={stage:'format-error',errorName:e.name};}
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For catch a broken json representation in a weather-observation practice sheet, with the hypothetical ‘Science & Art’ topic and count 12, the independently executed Node.js Web API test prints {“stage”:”format-error”,”errorName”:”SyntaxError”}. Its observable properties are specific: The response has a successful HTTP status, but the JSON parser makes a separate decision about the body grammar. An empty response body is not the same as a JSON empty array. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For catch a broken json representation in a weather-observation practice sheet, start with the code expression responsible for the result: Use an explicit 204 branch for a genuinely bodyless successful endpoint rather than hiding its meaning in a parsing catch. The controlled topic is ‘Science & Art’ and the mock count is 12. A loader has at least two contracts: receiving an acceptable HTTP response and decoding the advertised content. Different failures deserve different diagnoses. In this case the returned keys [‘stage’, ‘errorName’] are the evidence to inspect, not a claim that a real website is available. Start by identifying the unit of observation, then apply only the rule relevant to that unit..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “saying the network is broken when the server sent a successful status with malformed json.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this catch a broken json representation case in a weather-observation practice sheet, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A Punggol family can practise this with fictional numbers after dinner or over a weekend. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe catch a broken json representation in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Test a valid object, a broken object and an empty string separately. A Punggol family can practise this with fictional numbers after dinner or over a weekend.

CHAPTER 4 OF 20 · Back to contents

4. Handle responses with no content

Start with the answer: HTTP 204 means no response body; do not automatically call json() expecting an object.

A successful deletion or update might intentionally return no document. A bodyless success should update UI state according to the endpoint contract rather than inventing a record.

Common tempting error: Treating every 2xx response as proof there is JSON to parse.

Diagnostic for a parent or project partner: Does the endpoint promise data or merely that an operation completed?

Lab 1: handle responses with no content — a mock group presentation tracker

For a fictional family a mock group presentation tracker, the response is delayed but arrives intact. The topic is ‘Math + sketches’ and the controlled fixture uses count 6. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is http 204 means no response body; do not automatically call json() expecting an object.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=6;
const topic="Math + sketches";
const r=new Response(null,{status:204}); const result={status:r.status,ok:r.ok,bodyIsNull:r.body===null,canExpectJson:r.ok && r.status!==204 && r.status!==205};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For handle responses with no content in a mock group presentation tracker, with the hypothetical ‘Math + sketches’ topic and count 6, the independently executed Node.js Web API test prints {“status”:204,”ok”:true,”bodyIsNull”:true,”canExpectJson”:false}. Its observable properties are specific: Status 204 is combined with a null body under the web Response constructor. The field canExpectJson is a *toy contract decision*, not a guarantee of valid JSON. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For handle responses with no content in a mock group presentation tracker, start with the code expression responsible for the result: A real endpoint may use its own documented bodyless-success response contract. The controlled topic is ‘Math + sketches’ and the mock count is 6. A successful deletion or update might intentionally return no document. A bodyless success should update UI state according to the endpoint contract rather than inventing a record. In this case the returned keys [‘status’, ‘ok’, ‘bodyIsNull’, ‘canExpectJson’] are the evidence to inspect, not a claim that a real website is available. Check the case that would make a tempting shortcut wrong..

Check the boundary. First substitute topic “Art & Coding” for ‘Math + sketches’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this handle responses with no content case in a mock group presentation tracker, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. When the result surprises the learner, keep the counterexample in the practice notes. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: handle responses with no content — a volunteer-hours planning exercise

A pupil builds a little a volunteer-hours planning exercise and wants to understand handle responses with no content. With topic ‘Coastal habitats?’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is http 204 means no response body; do not automatically call json() expecting an object.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=15;
const topic="Coastal habitats?";
const r=new Response("{\"saved\":true}",{status:200}); const result={status:r.status,ok:r.ok,bodyIsNull:r.body===null,canExpectJson:r.ok && r.status!==204 && r.status!==205};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For handle responses with no content in a volunteer-hours planning exercise, with the hypothetical ‘Coastal habitats?’ topic and count 15, the independently executed Node.js Web API test prints {“status”:200,”ok”:true,”bodyIsNull”:false,”canExpectJson”:true}. Its observable properties are specific: Status 200 is combined with a small JSON string. The field canExpectJson is a *toy contract decision*, not a guarantee of valid JSON. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For handle responses with no content in a volunteer-hours planning exercise, start with the code expression responsible for the result: A real endpoint may use its own documented bodyless-success response contract. The controlled topic is ‘Coastal habitats?’ and the mock count is 15. A successful deletion or update might intentionally return no document. A bodyless success should update UI state according to the endpoint contract rather than inventing a record. In this case the returned keys [‘status’, ‘ok’, ‘bodyIsNull’, ‘canExpectJson’] are the evidence to inspect, not a claim that a real website is available. Name which records enter the calculation and which stay outside..

Check the boundary. Now replace the invented count 15 with 20, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this handle responses with no content case in a volunteer-hours planning exercise, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Treat a version-dependent result as a prompt to consult the current official manual. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: handle responses with no content — a weather-observation practice sheet

The make-believe records for a weather-observation practice sheet contain 10 observations under topic ‘Coastal habitats?’. A friend says the program has worked because the console displays something. Test handle responses with no content: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is http 204 means no response body; do not automatically call json() expecting an object.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=10;
const topic="Coastal habitats?";
const r=new Response(null,{status:205}); const result={status:r.status,ok:r.ok,bodyIsNull:r.body===null,canExpectJson:r.ok && r.status!==204 && r.status!==205};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For handle responses with no content in a weather-observation practice sheet, with the hypothetical ‘Coastal habitats?’ topic and count 10, the independently executed Node.js Web API test prints {“status”:205,”ok”:true,”bodyIsNull”:true,”canExpectJson”:false}. Its observable properties are specific: Status 205 is combined with a null body under the web Response constructor. The field canExpectJson is a *toy contract decision*, not a guarantee of valid JSON. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For handle responses with no content in a weather-observation practice sheet, start with the code expression responsible for the result: A real endpoint may use its own documented bodyless-success response contract. The controlled topic is ‘Coastal habitats?’ and the mock count is 10. A successful deletion or update might intentionally return no document. A bodyless success should update UI state according to the endpoint contract rather than inventing a record. In this case the returned keys [‘status’, ‘ok’, ‘bodyIsNull’, ‘canExpectJson’] are the evidence to inspect, not a claim that a real website is available. Write down the unsuccessful interpretation and explain why it fails..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a weather-observation practice sheet, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this handle responses with no content case in a weather-observation practice sheet, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. This is a proposed home exercise rather than a service or school claim. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: handle responses with no content — a shared family study calendar

After a shared family activity around a shared family study calendar, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Punggol eco-notes’ and the invented integer 2. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is http 204 means no response body; do not automatically call json() expecting an object.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=2;
const topic="Punggol eco-notes";
const r=new Response(null,{status:304}); const result={status:r.status,ok:r.ok,bodyIsNull:r.body===null,canExpectJson:r.ok && r.status!==204 && r.status!==205};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For handle responses with no content in a shared family study calendar, with the hypothetical ‘Punggol eco-notes’ topic and count 2, the independently executed Node.js Web API test prints {“status”:304,”ok”:false,”bodyIsNull”:true,”canExpectJson”:false}. Its observable properties are specific: Status 304 is combined with a null body under the web Response constructor. The field canExpectJson is a *toy contract decision*, not a guarantee of valid JSON. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For handle responses with no content in a shared family study calendar, start with the code expression responsible for the result: A real endpoint may use its own documented bodyless-success response contract. The controlled topic is ‘Punggol eco-notes’ and the mock count is 2. A successful deletion or update might intentionally return no document. A bodyless success should update UI state according to the endpoint contract rather than inventing a record. In this case the returned keys [‘status’, ‘ok’, ‘bodyIsNull’, ‘canExpectJson’] are the evidence to inspect, not a claim that a real website is available. Draw a miniature table and count the rows before calculating any summary..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “treating every 2xx response as proof there is json to parse.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this handle responses with no content case in a shared family study calendar, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A useful parent prompt is to request a prediction, not a memorised command. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe handle responses with no content in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Recognise a legitimate empty-body success without converting it into a parsing failure. No real pupil information is needed; the test data are deliberately imaginary.

CHAPTER 5 OF 20 · Back to contents

5. Read a response body only once

Start with the answer: Reading a Response body consumes its stream; a second direct read generally fails after the first successful consumption.

Debugging code can accidentally consume the only readable stream before the application parser gets it. Keep the parsed result or clone before consuming when truly necessary.

Common tempting error: Calling text() and then json() on the same original Response.

Diagnostic for a parent or project partner: Has the stream already been read or disturbed?

Lab 1: read a response body only once — a volunteer-hours planning exercise

For a fictional family a volunteer-hours planning exercise, the response is delayed but arrives intact. The topic is ‘Science & Art’ and the controlled fixture uses count 13. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is reading a response body consumes its stream; a second direct read generally fails after the first successful consumption.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=13;
const topic="Science & Art";
const r=new Response("chapter-4-case-0-Science & Art"); const before=r.bodyUsed; const first=await r.text(); let second; try{await r.text();second='unexpected-success';}catch(e){second=e.name;} const result={before,after:r.bodyUsed,first,second};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For read a response body only once in a volunteer-hours planning exercise, with the hypothetical ‘Science & Art’ topic and count 13, the independently executed Node.js Web API test prints {“before”:false,”after”:true,”first”:”chapter-4-case-0-Science & Art”,”second”:”TypeError”}. Its observable properties are specific: The test reads the same original Response body twice. The first successful text() call consumes the readable stream, so the second attempt is rejected by the runtime. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For read a response body only once in a volunteer-hours planning exercise, start with the code expression responsible for the result: The lesson is about a stream lifecycle, not about whether the server response was grammatically valid JSON. The controlled topic is ‘Science & Art’ and the mock count is 13. Debugging code can accidentally consume the only readable stream before the application parser gets it. Keep the parsed result or clone before consuming when truly necessary. In this case the returned keys [‘before’, ‘after’, ‘first’, ‘second’] are the evidence to inspect, not a claim that a real website is available. Compare the desired answer with an alternative that looks similar but measures something else..

Check the boundary. First substitute topic “Art & Coding” for ‘Science & Art’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this read a response body only once case in a volunteer-hours planning exercise, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The next step should be one small controlled variation, not ten simultaneous edits. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: read a response body only once — a public-transport timing experiment

A pupil builds a little a public-transport timing experiment and wants to understand read a response body only once. With topic ‘Math + sketches’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is reading a response body consumes its stream; a second direct read generally fails after the first successful consumption.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=5;
const topic="Math + sketches";
const r=new Response("chapter-4-case-3-Math + sketches"); const before=r.bodyUsed; const first=await r.text(); let second; try{await r.text();second='unexpected-success';}catch(e){second=e.name;} const result={before,after:r.bodyUsed,first,second};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For read a response body only once in a public-transport timing experiment, with the hypothetical ‘Math + sketches’ topic and count 5, the independently executed Node.js Web API test prints {“before”:false,”after”:true,”first”:”chapter-4-case-3-Math + sketches”,”second”:”TypeError”}. Its observable properties are specific: The test reads the same original Response body twice. The first successful text() call consumes the readable stream, so the second attempt is rejected by the runtime. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For read a response body only once in a public-transport timing experiment, start with the code expression responsible for the result: The lesson is about a stream lifecycle, not about whether the server response was grammatically valid JSON. The controlled topic is ‘Math + sketches’ and the mock count is 5. Debugging code can accidentally consume the only readable stream before the application parser gets it. Keep the parsed result or clone before consuming when truly necessary. In this case the returned keys [‘before’, ‘after’, ‘first’, ‘second’] are the evidence to inspect, not a claim that a real website is available. Cross-check with an independent hand calculation using the smallest workable values..

Check the boundary. Now replace the invented count 5 with 10, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this read a response body only once case in a public-transport timing experiment, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A clear explanation is more valuable than guessing an answer from the display. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: read a response body only once — a shared family study calendar

The make-believe records for a shared family study calendar contain 17 observations under topic ‘Math + sketches’. A friend says the program has worked because the console displays something. Test read a response body only once: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is reading a response body consumes its stream; a second direct read generally fails after the first successful consumption.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=17;
const topic="Math + sketches";
const r=new Response("chapter-4-case-7-Math + sketches"); const before=r.bodyUsed; const first=await r.text(); let second; try{await r.text();second='unexpected-success';}catch(e){second=e.name;} const result={before,after:r.bodyUsed,first,second};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For read a response body only once in a shared family study calendar, with the hypothetical ‘Math + sketches’ topic and count 17, the independently executed Node.js Web API test prints {“before”:false,”after”:true,”first”:”chapter-4-case-7-Math + sketches”,”second”:”TypeError”}. Its observable properties are specific: The test reads the same original Response body twice. The first successful text() call consumes the readable stream, so the second attempt is rejected by the runtime. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For read a response body only once in a shared family study calendar, start with the code expression responsible for the result: The lesson is about a stream lifecycle, not about whether the server response was grammatically valid JSON. The controlled topic is ‘Math + sketches’ and the mock count is 17. Debugging code can accidentally consume the only readable stream before the application parser gets it. Keep the parsed result or clone before consuming when truly necessary. In this case the returned keys [‘before’, ‘after’, ‘first’, ‘second’] are the evidence to inspect, not a claim that a real website is available. Carry the result back to the family’s original decision, without claiming more than the data support..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a shared family study calendar, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this read a response body only once case in a shared family study calendar, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. No real pupil information is needed; the test data are deliberately imaginary. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: read a response body only once — a weekend reading journal

After a shared family activity around a weekend reading journal, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Coastal habitats?’ and the invented integer 9. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is reading a response body consumes its stream; a second direct read generally fails after the first successful consumption.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=9;
const topic="Coastal habitats?";
const r=new Response("chapter-4-case-10-Coastal habitats?"); const before=r.bodyUsed; const first=await r.text(); let second; try{await r.text();second='unexpected-success';}catch(e){second=e.name;} const result={before,after:r.bodyUsed,first,second};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For read a response body only once in a weekend reading journal, with the hypothetical ‘Coastal habitats?’ topic and count 9, the independently executed Node.js Web API test prints {“before”:false,”after”:true,”first”:”chapter-4-case-10-Coastal habitats?”,”second”:”TypeError”}. Its observable properties are specific: The test reads the same original Response body twice. The first successful text() call consumes the readable stream, so the second attempt is rejected by the runtime. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For read a response body only once in a weekend reading journal, start with the code expression responsible for the result: The lesson is about a stream lifecycle, not about whether the server response was grammatically valid JSON. The controlled topic is ‘Coastal habitats?’ and the mock count is 9. Debugging code can accidentally consume the only readable stream before the application parser gets it. Keep the parsed result or clone before consuming when truly necessary. In this case the returned keys [‘before’, ‘after’, ‘first’, ‘second’] are the evidence to inspect, not a claim that a real website is available. Explain the result in ordinary language before trusting a convenient display..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “calling text() and then json() on the same original response.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this read a response body only once case in a weekend reading journal, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. When the result surprises the learner, keep the counterexample in the practice notes. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe read a response body only once in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Predict bodyUsed before and after reading a test response. A useful parent prompt is to request a prediction, not a memorised command.

CHAPTER 6 OF 20 · Back to contents

6. Clone before two intentional reads

Start with the answer: Response.clone() is available for independently reading a body in two ways if cloning happens before the stream is consumed.

Cloning is an advanced choice and can increase buffering. For most home exercises, parsing once and retaining the object is clearer.

Common tempting error: Cloning after consumption or treating a clone as a free solution for huge streaming responses.

Diagnostic for a parent or project partner: Is there a genuine second consumer that justifies the cloned stream?

Lab 1: clone before two intentional reads — a public-transport timing experiment

For a fictional family a public-transport timing experiment, the response is delayed but arrives intact. The topic is ‘Punggol eco-notes’ and the controlled fixture uses count 3. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is response.clone() is available for independently reading a body in two ways if cloning happens before the stream is consumed.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=3;
const topic="Punggol eco-notes";
const r=new Response("\"{\\\"topic\\\":\\\"Punggol eco-notes\\\",\\\"minutes\\\":3}\"");const copy=r.clone();const a=await r.text();const b=await copy.json(); const result={bodyUsed:r.bodyUsed,copyBodyUsed:copy.bodyUsed,textLength:a.length,parsedTopic:b.topic,minutes:b.minutes};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For clone before two intentional reads in a public-transport timing experiment, with the hypothetical ‘Punggol eco-notes’ topic and count 3, the independently executed Node.js Web API test prints {“bodyUsed”:true,”copyBodyUsed”:true,”textLength”:49}. Its observable properties are specific: Clone before consuming. The original is read as text; the cloned response is parsed as JSON. Both streams become consumed independently. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For clone before two intentional reads in a public-transport timing experiment, start with the code expression responsible for the result: Avoid building unnecessary clones of huge streams. Most educational apps only need one supported representation. The controlled topic is ‘Punggol eco-notes’ and the mock count is 3. Cloning is an advanced choice and can increase buffering. For most home exercises, parsing once and retaining the object is clearer. In this case the returned keys [‘bodyUsed’, ‘copyBodyUsed’, ‘textLength’] are the evidence to inspect, not a claim that a real website is available. Keep the input unchanged while adjusting a single condition..

Check the boundary. First substitute topic “Art & Coding” for ‘Punggol eco-notes’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this clone before two intentional reads case in a public-transport timing experiment, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Save the example so the learner can rerun it with a fresh number next week. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: clone before two intentional reads — a fictional club membership register

A pupil builds a little a fictional club membership register and wants to understand clone before two intentional reads. With topic ‘Science & Art’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is response.clone() is available for independently reading a body in two ways if cloning happens before the stream is consumed.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=12;
const topic="Science & Art";
const r=new Response("\"{\\\"topic\\\":\\\"Science & Art\\\",\\\"minutes\\\":12}\"");const copy=r.clone();const a=await r.text();const b=await copy.json(); const result={bodyUsed:r.bodyUsed,copyBodyUsed:copy.bodyUsed,textLength:a.length,parsedTopic:b.topic,minutes:b.minutes};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For clone before two intentional reads in a fictional club membership register, with the hypothetical ‘Science & Art’ topic and count 12, the independently executed Node.js Web API test prints {“bodyUsed”:true,”copyBodyUsed”:true,”textLength”:46}. Its observable properties are specific: Clone before consuming. The original is read as text; the cloned response is parsed as JSON. Both streams become consumed independently. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For clone before two intentional reads in a fictional club membership register, start with the code expression responsible for the result: Avoid building unnecessary clones of huge streams. Most educational apps only need one supported representation. The controlled topic is ‘Science & Art’ and the mock count is 12. Cloning is an advanced choice and can increase buffering. For most home exercises, parsing once and retaining the object is clearer. In this case the returned keys [‘bodyUsed’, ‘copyBodyUsed’, ‘textLength’] are the evidence to inspect, not a claim that a real website is available. Predict the behaviour before running a test; the difference between prediction and result is the learning target..

Check the boundary. Now replace the invented count 12 with 17, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this clone before two intentional reads case in a fictional club membership register, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. This is a proposed home exercise rather than a service or school claim. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: clone before two intentional reads — a weekend reading journal

The make-believe records for a weekend reading journal contain 7 observations under topic ‘Science & Art’. A friend says the program has worked because the console displays something. Test clone before two intentional reads: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is response.clone() is available for independently reading a body in two ways if cloning happens before the stream is consumed.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=7;
const topic="Science & Art";
const r=new Response("\"{\\\"topic\\\":\\\"Science & Art\\\",\\\"minutes\\\":7}\"");const copy=r.clone();const a=await r.text();const b=await copy.json(); const result={bodyUsed:r.bodyUsed,copyBodyUsed:copy.bodyUsed,textLength:a.length,parsedTopic:b.topic,minutes:b.minutes};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For clone before two intentional reads in a weekend reading journal, with the hypothetical ‘Science & Art’ topic and count 7, the independently executed Node.js Web API test prints {“bodyUsed”:true,”copyBodyUsed”:true,”textLength”:45}. Its observable properties are specific: Clone before consuming. The original is read as text; the cloned response is parsed as JSON. Both streams become consumed independently. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For clone before two intentional reads in a weekend reading journal, start with the code expression responsible for the result: Avoid building unnecessary clones of huge streams. Most educational apps only need one supported representation. The controlled topic is ‘Science & Art’ and the mock count is 7. Cloning is an advanced choice and can increase buffering. For most home exercises, parsing once and retaining the object is clearer. In this case the returned keys [‘bodyUsed’, ‘copyBodyUsed’, ‘textLength’] are the evidence to inspect, not a claim that a real website is available. Start by identifying the unit of observation, then apply only the rule relevant to that unit..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a weekend reading journal, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this clone before two intentional reads case in a weekend reading journal, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The goal is not to finish a huge worksheet; it is to explain one reliable decision. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: clone before two intentional reads — a simulated science-club project

After a shared family activity around a simulated science-club project, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Math + sketches’ and the invented integer 16. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is response.clone() is available for independently reading a body in two ways if cloning happens before the stream is consumed.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=16;
const topic="Math + sketches";
const r=new Response("\"{\\\"topic\\\":\\\"Math + sketches\\\",\\\"minutes\\\":16}\"");const copy=r.clone();const a=await r.text();const b=await copy.json(); const result={bodyUsed:r.bodyUsed,copyBodyUsed:copy.bodyUsed,textLength:a.length,parsedTopic:b.topic,minutes:b.minutes};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For clone before two intentional reads in a simulated science-club project, with the hypothetical ‘Math + sketches’ topic and count 16, the independently executed Node.js Web API test prints {“bodyUsed”:true,”copyBodyUsed”:true,”textLength”:48}. Its observable properties are specific: Clone before consuming. The original is read as text; the cloned response is parsed as JSON. Both streams become consumed independently. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For clone before two intentional reads in a simulated science-club project, start with the code expression responsible for the result: Avoid building unnecessary clones of huge streams. Most educational apps only need one supported representation. The controlled topic is ‘Math + sketches’ and the mock count is 16. Cloning is an advanced choice and can increase buffering. For most home exercises, parsing once and retaining the object is clearer. In this case the returned keys [‘bodyUsed’, ‘copyBodyUsed’, ‘textLength’] are the evidence to inspect, not a claim that a real website is available. Check the case that would make a tempting shortcut wrong..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “cloning after consumption or treating a clone as a free solution for huge streaming responses.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this clone before two intentional reads case in a simulated science-club project, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The next step should be one small controlled variation, not ten simultaneous edits. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe clone before two intentional reads in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Demonstrate a two-reader case and then simplify it to a single read. The goal is not to finish a huge worksheet; it is to explain one reliable decision.

CHAPTER 7 OF 20 · Back to contents

7. Choose text rather than JSON when promised

Start with the answer: Use text() for plain text, json() for JSON, and another suitable reader for a different representation.

A server can return an ordinary notice. Attempting to decode that notice as JSON confuses media format with meaning. A page should display untrusted strings as text, not raw HTML.

Common tempting error: Forcing all fetch results through json() regardless of the server contract.

Diagnostic for a parent or project partner: What content type and body shape were promised?

Lab 1: choose text rather than json when promised — a fictional club membership register

For a fictional family a fictional club membership register, the response is delayed but arrives intact. The topic is ‘Coastal habitats?’ and the controlled fixture uses count 10. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is use text() for plain text, json() for json, and another suitable reader for a different representation.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=10;
const topic="Coastal habitats?";
const r=new Response("Coastal habitats? — 10 minutes",{headers:{'Content-Type':'text/plain; charset=utf-8'}});const notice=await r.text();const result={notice,type:r.headers.get('content-type'),length:notice.length};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For choose text rather than json when promised in a fictional club membership register, with the hypothetical ‘Coastal habitats?’ topic and count 10, the independently executed Node.js Web API test prints {“notice”:”Coastal habitats? — 10 minutes”,”type”:”text/plain; charset=utf-8″,”length”:30}. Its observable properties are specific: A human-readable notice is read as text and preserved, including punctuation. If placed into a real webpage, it should be rendered as text content, not assumed safe HTML. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For choose text rather than json when promised in a fictional club membership register, start with the code expression responsible for the result: Reading binary content, blobs or images requires a different body-reader choice; do not conflate their formats. The controlled topic is ‘Coastal habitats?’ and the mock count is 10. A server can return an ordinary notice. Attempting to decode that notice as JSON confuses media format with meaning. A page should display untrusted strings as text, not raw HTML. In this case the returned keys [‘notice’, ‘type’, ‘length’] are the evidence to inspect, not a claim that a real website is available. Name which records enter the calculation and which stay outside..

Check the boundary. First substitute topic “Art & Coding” for ‘Coastal habitats?’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this choose text rather than json when promised case in a fictional club membership register, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Try this on a small, invented table before using any real schoolwork. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: choose text rather than json when promised — a fictional class activity log

A pupil builds a little a fictional class activity log and wants to understand choose text rather than json when promised. With topic ‘Punggol eco-notes’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is use text() for plain text, json() for json, and another suitable reader for a different representation.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=2;
const topic="Punggol eco-notes";
const r=new Response("Punggol eco-notes — 2 minutes",{headers:{'Content-Type':'text/plain; charset=utf-8'}});const notice=await r.text();const result={notice,type:r.headers.get('content-type'),length:notice.length};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For choose text rather than json when promised in a fictional class activity log, with the hypothetical ‘Punggol eco-notes’ topic and count 2, the independently executed Node.js Web API test prints {“notice”:”Punggol eco-notes — 2 minutes”,”type”:”text/plain; charset=utf-8″,”length”:29}. Its observable properties are specific: A human-readable notice is read as text and preserved, including punctuation. If placed into a real webpage, it should be rendered as text content, not assumed safe HTML. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For choose text rather than json when promised in a fictional class activity log, start with the code expression responsible for the result: Reading binary content, blobs or images requires a different body-reader choice; do not conflate their formats. The controlled topic is ‘Punggol eco-notes’ and the mock count is 2. A server can return an ordinary notice. Attempting to decode that notice as JSON confuses media format with meaning. A page should display untrusted strings as text, not raw HTML. In this case the returned keys [‘notice’, ‘type’, ‘length’] are the evidence to inspect, not a claim that a real website is available. Ask whether the structure remains valid when the number of records doubles..

Check the boundary. Now replace the invented count 2 with 7, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this choose text rather than json when promised case in a fictional class activity log, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. No real pupil information is needed; the test data are deliberately imaginary. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: choose text rather than json when promised — a simulated science-club project

The make-believe records for a simulated science-club project contain 14 observations under topic ‘Punggol eco-notes’. A friend says the program has worked because the console displays something. Test choose text rather than json when promised: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is use text() for plain text, json() for json, and another suitable reader for a different representation.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=14;
const topic="Punggol eco-notes";
const r=new Response("Punggol eco-notes — 14 minutes",{headers:{'Content-Type':'text/plain; charset=utf-8'}});const notice=await r.text();const result={notice,type:r.headers.get('content-type'),length:notice.length};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For choose text rather than json when promised in a simulated science-club project, with the hypothetical ‘Punggol eco-notes’ topic and count 14, the independently executed Node.js Web API test prints {“notice”:”Punggol eco-notes — 14 minutes”,”type”:”text/plain; charset=utf-8″,”length”:30}. Its observable properties are specific: A human-readable notice is read as text and preserved, including punctuation. If placed into a real webpage, it should be rendered as text content, not assumed safe HTML. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For choose text rather than json when promised in a simulated science-club project, start with the code expression responsible for the result: Reading binary content, blobs or images requires a different body-reader choice; do not conflate their formats. The controlled topic is ‘Punggol eco-notes’ and the mock count is 14. A server can return an ordinary notice. Attempting to decode that notice as JSON confuses media format with meaning. A page should display untrusted strings as text, not raw HTML. In this case the returned keys [‘notice’, ‘type’, ‘length’] are the evidence to inspect, not a claim that a real website is available. Draw a miniature table and count the rows before calculating any summary..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a simulated science-club project, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this choose text rather than json when promised case in a simulated science-club project, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Independent checking beats a polished screen that nobody can explain. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: choose text rather than json when promised — a recycled-materials tally

After a shared family activity around a recycled-materials tally, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Science & Art’ and the invented integer 6. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is use text() for plain text, json() for json, and another suitable reader for a different representation.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=6;
const topic="Science & Art";
const r=new Response("Science & Art — 6 minutes",{headers:{'Content-Type':'text/plain; charset=utf-8'}});const notice=await r.text();const result={notice,type:r.headers.get('content-type'),length:notice.length};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For choose text rather than json when promised in a recycled-materials tally, with the hypothetical ‘Science & Art’ topic and count 6, the independently executed Node.js Web API test prints {“notice”:”Science & Art — 6 minutes”,”type”:”text/plain; charset=utf-8″,”length”:25}. Its observable properties are specific: A human-readable notice is read as text and preserved, including punctuation. If placed into a real webpage, it should be rendered as text content, not assumed safe HTML. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For choose text rather than json when promised in a recycled-materials tally, start with the code expression responsible for the result: Reading binary content, blobs or images requires a different body-reader choice; do not conflate their formats. The controlled topic is ‘Science & Art’ and the mock count is 6. A server can return an ordinary notice. Attempting to decode that notice as JSON confuses media format with meaning. A page should display untrusted strings as text, not raw HTML. In this case the returned keys [‘notice’, ‘type’, ‘length’] are the evidence to inspect, not a claim that a real website is available. Compare the desired answer with an alternative that looks similar but measures something else..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “forcing all fetch results through json() regardless of the server contract.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this choose text rather than json when promised case in a recycled-materials tally, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Save the example so the learner can rerun it with a fresh number next week. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe choose text rather than json when promised in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Ask the learner to write a one-line format contract before selecting a body reader. When the result surprises the learner, keep the counterexample in the practice notes.

CHAPTER 8 OF 20 · Back to contents

8. Inspect Content-Type without trusting it blindly

Start with the answer: A Content-Type header describes the claimed media type; it does not prove the body is well-formed or safe.

A robust client can reject an unexpected representation early, but it still needs to parse and validate accepted data. Headers can be wrong or absent, particularly in mocks.

Common tempting error: Checking only the header and skipping the actual content check.

Diagnostic for a parent or project partner: Does the declared type match both the requested resource and its body?

Lab 1: inspect content-type without trusting it blindly — a fictional class activity log

For a fictional family a fictional class activity log, the response is delayed but arrives intact. The topic is ‘Math + sketches’ and the controlled fixture uses count 17. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a content-type header describes the claimed media type; it does not prove the body is well-formed or safe.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=17;
const topic="Math + sketches";
const r=new Response("\"{\\\"minutes\\\":17}\"",{headers:{'Content-Type':"application/json"}});const mime=r.headers.get('content-type')||'(missing)';const expected=mime.toLowerCase().includes('application/json');const data=await r.json();const result={mime,headerSaysJson:expected,parsedMinutes:data.minutes};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For inspect content-type without trusting it blindly in a fictional class activity log, with the hypothetical ‘Math + sketches’ topic and count 17, the independently executed Node.js Web API test prints {“mime”:”application/json”,”headerSaysJson”:true}. Its observable properties are specific: The body decodes as JSON in each case, but the declared metadata changes. A +json structured subtype such as application/problem+json also deserves an explicit contract rather than a brittle string equality test. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For inspect content-type without trusting it blindly in a fictional class activity log, start with the code expression responsible for the result: A successful JSON parse proves syntax, not that the data is truthful or authorised. The controlled topic is ‘Math + sketches’ and the mock count is 17. A robust client can reject an unexpected representation early, but it still needs to parse and validate accepted data. Headers can be wrong or absent, particularly in mocks. In this case the returned keys [‘mime’, ‘headerSaysJson’] are the evidence to inspect, not a claim that a real website is available. Cross-check with an independent hand calculation using the smallest workable values..

Check the boundary. First substitute topic “Art & Coding” for ‘Math + sketches’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this inspect content-type without trusting it blindly case in a fictional class activity log, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A Punggol family can practise this with fictional numbers after dinner or over a weekend. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: inspect content-type without trusting it blindly — a coastal ecology observation workbook

A pupil builds a little a coastal ecology observation workbook and wants to understand inspect content-type without trusting it blindly. With topic ‘Coastal habitats?’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a content-type header describes the claimed media type; it does not prove the body is well-formed or safe.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=9;
const topic="Coastal habitats?";
const r=new Response("\"{\\\"minutes\\\":9}\"",{headers:{'Content-Type':"text/plain"}});const mime=r.headers.get('content-type')||'(missing)';const expected=mime.toLowerCase().includes('application/json');const data=await r.json();const result={mime,headerSaysJson:expected,parsedMinutes:data.minutes};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For inspect content-type without trusting it blindly in a coastal ecology observation workbook, with the hypothetical ‘Coastal habitats?’ topic and count 9, the independently executed Node.js Web API test prints {“mime”:”text/plain”,”headerSaysJson”:false}. Its observable properties are specific: The body decodes as JSON in each case, but the declared metadata changes. A +json structured subtype such as application/problem+json also deserves an explicit contract rather than a brittle string equality test. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For inspect content-type without trusting it blindly in a coastal ecology observation workbook, start with the code expression responsible for the result: A successful JSON parse proves syntax, not that the data is truthful or authorised. The controlled topic is ‘Coastal habitats?’ and the mock count is 9. A robust client can reject an unexpected representation early, but it still needs to parse and validate accepted data. Headers can be wrong or absent, particularly in mocks. In this case the returned keys [‘mime’, ‘headerSaysJson’] are the evidence to inspect, not a claim that a real website is available. Write down the unsuccessful interpretation and explain why it fails..

Check the boundary. Now replace the invented count 9 with 14, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this inspect content-type without trusting it blindly case in a coastal ecology observation workbook, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The goal is not to finish a huge worksheet; it is to explain one reliable decision. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: inspect content-type without trusting it blindly — a recycled-materials tally

The make-believe records for a recycled-materials tally contain 4 observations under topic ‘Coastal habitats?’. A friend says the program has worked because the console displays something. Test inspect content-type without trusting it blindly: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a content-type header describes the claimed media type; it does not prove the body is well-formed or safe.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=4;
const topic="Coastal habitats?";
const r=new Response("\"{\\\"minutes\\\":4}\"",{headers:{'Content-Type':"application/problem+json"}});const mime=r.headers.get('content-type')||'(missing)';const expected=mime.toLowerCase().includes('application/json');const data=await r.json();const result={mime,headerSaysJson:expected,parsedMinutes:data.minutes};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For inspect content-type without trusting it blindly in a recycled-materials tally, with the hypothetical ‘Coastal habitats?’ topic and count 4, the independently executed Node.js Web API test prints {“mime”:”application/problem+json”,”headerSaysJson”:false}. Its observable properties are specific: The body decodes as JSON in each case, but the declared metadata changes. A +json structured subtype such as application/problem+json also deserves an explicit contract rather than a brittle string equality test. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For inspect content-type without trusting it blindly in a recycled-materials tally, start with the code expression responsible for the result: A successful JSON parse proves syntax, not that the data is truthful or authorised. The controlled topic is ‘Coastal habitats?’ and the mock count is 4. A robust client can reject an unexpected representation early, but it still needs to parse and validate accepted data. Headers can be wrong or absent, particularly in mocks. In this case the returned keys [‘mime’, ‘headerSaysJson’] are the evidence to inspect, not a claim that a real website is available. Explain the result in ordinary language before trusting a convenient display..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a recycled-materials tally, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this inspect content-type without trusting it blindly case in a recycled-materials tally, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Treat a version-dependent result as a prompt to consult the current official manual. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: inspect content-type without trusting it blindly — a home garden observation chart

After a shared family activity around a home garden observation chart, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Punggol eco-notes’ and the invented integer 13. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a content-type header describes the claimed media type; it does not prove the body is well-formed or safe.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=13;
const topic="Punggol eco-notes";
const r=new Response("\"{\\\"minutes\\\":13}\"",{headers:{}});const mime=r.headers.get('content-type')||'(missing)';const expected=mime.toLowerCase().includes('application/json');const data=await r.json();const result={mime,headerSaysJson:expected,parsedMinutes:data.minutes};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For inspect content-type without trusting it blindly in a home garden observation chart, with the hypothetical ‘Punggol eco-notes’ topic and count 13, the independently executed Node.js Web API test prints {“mime”:”text/plain;charset=UTF-8″,”headerSaysJson”:false}. Its observable properties are specific: The body decodes as JSON in each case, but the declared metadata changes. A +json structured subtype such as application/problem+json also deserves an explicit contract rather than a brittle string equality test. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For inspect content-type without trusting it blindly in a home garden observation chart, start with the code expression responsible for the result: A successful JSON parse proves syntax, not that the data is truthful or authorised. The controlled topic is ‘Punggol eco-notes’ and the mock count is 13. A robust client can reject an unexpected representation early, but it still needs to parse and validate accepted data. Headers can be wrong or absent, particularly in mocks. In this case the returned keys [‘mime’, ‘headerSaysJson’] are the evidence to inspect, not a claim that a real website is available. Keep the input unchanged while adjusting a single condition..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “checking only the header and skipping the actual content check.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this inspect content-type without trusting it blindly case in a home garden observation chart, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Try this on a small, invented table before using any real schoolwork. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe inspect content-type without trusting it blindly in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Build two responses with the same body but different headers to isolate the metadata decision. Independent checking beats a polished screen that nobody can explain.

CHAPTER 9 OF 20 · Back to contents

9. Encode search queries with URLSearchParams

Start with the answer: URL and URLSearchParams safely encode punctuation and spaces in query parameter values.

A fictional topic such as Science & Art has an ampersand that would split a hand-built query. The goal is preserving the exact input value, not hiding it in a URL string.

Common tempting error: Concatenating an unencoded user label after a question mark.

Diagnostic for a parent or project partner: How can you recover the original value from the constructed URL?

Lab 1: encode search queries with urlsearchparams — a coastal ecology observation workbook

For a fictional family a coastal ecology observation workbook, the response is delayed but arrives intact. The topic is ‘Science & Art’ and the controlled fixture uses count 7. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is url and urlsearchparams safely encode punctuation and spaces in query parameter values.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=7;
const topic="Science & Art";
const u=new URL('/activities','https://practice.invalid');u.searchParams.set('topic',topic);u.searchParams.set('count',String(count));const result={query:u.search,decoded:u.searchParams.get('topic'),count:u.searchParams.get('count')};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For encode search queries with urlsearchparams in a coastal ecology observation workbook, with the hypothetical ‘Science & Art’ topic and count 7, the independently executed Node.js Web API test prints {“query”:”?topic=Science+%26+Art&count=7″,”decoded”:”Science & Art”,”count”:”7″}. Its observable properties are specific: URLSearchParams turns an arbitrary topic label into one query-parameter value and preserves it when decoded. The .invalid domain is intentionally non-routable; no remote request is attempted. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For encode search queries with urlsearchparams in a coastal ecology observation workbook, start with the code expression responsible for the result: Test a literal plus sign and ampersand. Manual concatenation can change one intended value into multiple accidental parameters. The controlled topic is ‘Science & Art’ and the mock count is 7. A fictional topic such as Science & Art has an ampersand that would split a hand-built query. The goal is preserving the exact input value, not hiding it in a URL string. In this case the returned keys [‘query’, ‘decoded’, ‘count’] are the evidence to inspect, not a claim that a real website is available. Predict the behaviour before running a test; the difference between prediction and result is the learning target..

Check the boundary. First substitute topic “Art & Coding” for ‘Science & Art’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this encode search queries with urlsearchparams case in a coastal ecology observation workbook, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A useful parent prompt is to request a prediction, not a memorised command. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: encode search queries with urlsearchparams — an after-CCA practice planner

A pupil builds a little an after-CCA practice planner and wants to understand encode search queries with urlsearchparams. With topic ‘Math + sketches’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is url and urlsearchparams safely encode punctuation and spaces in query parameter values.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=16;
const topic="Math + sketches";
const u=new URL('/activities','https://practice.invalid');u.searchParams.set('topic',topic);u.searchParams.set('count',String(count));const result={query:u.search,decoded:u.searchParams.get('topic'),count:u.searchParams.get('count')};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For encode search queries with urlsearchparams in an after-CCA practice planner, with the hypothetical ‘Math + sketches’ topic and count 16, the independently executed Node.js Web API test prints {“query”:”?topic=Math+%2B+sketches&count=16″,”decoded”:”Math + sketches”,”count”:”16″}. Its observable properties are specific: URLSearchParams turns an arbitrary topic label into one query-parameter value and preserves it when decoded. The .invalid domain is intentionally non-routable; no remote request is attempted. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For encode search queries with urlsearchparams in an after-CCA practice planner, start with the code expression responsible for the result: Test a literal plus sign and ampersand. Manual concatenation can change one intended value into multiple accidental parameters. The controlled topic is ‘Math + sketches’ and the mock count is 16. A fictional topic such as Science & Art has an ampersand that would split a hand-built query. The goal is preserving the exact input value, not hiding it in a URL string. In this case the returned keys [‘query’, ‘decoded’, ‘count’] are the evidence to inspect, not a claim that a real website is available. Carry the result back to the family’s original decision, without claiming more than the data support..

Check the boundary. Now replace the invented count 16 with 21, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this encode search queries with urlsearchparams case in an after-CCA practice planner, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Independent checking beats a polished screen that nobody can explain. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: encode search queries with urlsearchparams — a home garden observation chart

The make-believe records for a home garden observation chart contain 11 observations under topic ‘Math + sketches’. A friend says the program has worked because the console displays something. Test encode search queries with urlsearchparams: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is url and urlsearchparams safely encode punctuation and spaces in query parameter values.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=11;
const topic="Math + sketches";
const u=new URL('/activities','https://practice.invalid');u.searchParams.set('topic',topic);u.searchParams.set('count',String(count));const result={query:u.search,decoded:u.searchParams.get('topic'),count:u.searchParams.get('count')};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For encode search queries with urlsearchparams in a home garden observation chart, with the hypothetical ‘Math + sketches’ topic and count 11, the independently executed Node.js Web API test prints {“query”:”?topic=Math+%2B+sketches&count=11″,”decoded”:”Math + sketches”,”count”:”11″}. Its observable properties are specific: URLSearchParams turns an arbitrary topic label into one query-parameter value and preserves it when decoded. The .invalid domain is intentionally non-routable; no remote request is attempted. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For encode search queries with urlsearchparams in a home garden observation chart, start with the code expression responsible for the result: Test a literal plus sign and ampersand. Manual concatenation can change one intended value into multiple accidental parameters. The controlled topic is ‘Math + sketches’ and the mock count is 11. A fictional topic such as Science & Art has an ampersand that would split a hand-built query. The goal is preserving the exact input value, not hiding it in a URL string. In this case the returned keys [‘query’, ‘decoded’, ‘count’] are the evidence to inspect, not a claim that a real website is available. Check the case that would make a tempting shortcut wrong..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a home garden observation chart, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this encode search queries with urlsearchparams case in a home garden observation chart, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A clear explanation is more valuable than guessing an answer from the display. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: encode search queries with urlsearchparams — a mock fundraising spreadsheet

After a shared family activity around a mock fundraising spreadsheet, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Coastal habitats?’ and the invented integer 3. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is url and urlsearchparams safely encode punctuation and spaces in query parameter values.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=3;
const topic="Coastal habitats?";
const u=new URL('/activities','https://practice.invalid');u.searchParams.set('topic',topic);u.searchParams.set('count',String(count));const result={query:u.search,decoded:u.searchParams.get('topic'),count:u.searchParams.get('count')};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For encode search queries with urlsearchparams in a mock fundraising spreadsheet, with the hypothetical ‘Coastal habitats?’ topic and count 3, the independently executed Node.js Web API test prints {“query”:”?topic=Coastal+habitats%3F&count=3″,”decoded”:”Coastal habitats?”,”count”:”3″}. Its observable properties are specific: URLSearchParams turns an arbitrary topic label into one query-parameter value and preserves it when decoded. The .invalid domain is intentionally non-routable; no remote request is attempted. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For encode search queries with urlsearchparams in a mock fundraising spreadsheet, start with the code expression responsible for the result: Test a literal plus sign and ampersand. Manual concatenation can change one intended value into multiple accidental parameters. The controlled topic is ‘Coastal habitats?’ and the mock count is 3. A fictional topic such as Science & Art has an ampersand that would split a hand-built query. The goal is preserving the exact input value, not hiding it in a URL string. In this case the returned keys [‘query’, ‘decoded’, ‘count’] are the evidence to inspect, not a claim that a real website is available. Name which records enter the calculation and which stay outside..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “concatenating an unencoded user label after a question mark.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this encode search queries with urlsearchparams case in a mock fundraising spreadsheet, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A Punggol family can practise this with fictional numbers after dinner or over a weekend. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe encode search queries with urlsearchparams in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Encode then decode a topic with ampersand, plus, slash and Unicode. The next step should be one small controlled variation, not ten simultaneous edits.

CHAPTER 10 OF 20 · Back to contents

10. Build JSON POST requests deliberately

Start with the answer: When an API expects JSON, use JSON.stringify for the body and identify the representation with the appropriate Content-Type.

A POST may change server state. Build and inspect a Request object locally instead of posting fictional test records to unrelated services.

Common tempting error: Writing a JavaScript object directly into request body and assuming it becomes JSON.

Diagnostic for a parent or project partner: Which exact bytes and method would reach a server under this hypothetical contract?

Lab 1: build json post requests deliberately — an after-CCA practice planner

For a fictional family an after-CCA practice planner, the response is delayed but arrives intact. The topic is ‘Punggol eco-notes’ and the controlled fixture uses count 14. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is when an api expects json, use json.stringify for the body and identify the representation with the appropriate content-type.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=14;
const topic="Punggol eco-notes";
const data={topic,minutes:count};const r=new Request('https://practice.invalid/activities',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});const body=JSON.parse(await r.text());const result={method:r.method,media:r.headers.get('content-type'),body};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For build json post requests deliberately in an after-CCA practice planner, with the hypothetical ‘Punggol eco-notes’ topic and count 14, the independently executed Node.js Web API test prints {“method”:”POST”,”media”:”application/json”,”body”:{“topic”:”Punggol eco-notes”,”minutes”:14}}. Its observable properties are specific: A new Request is inspected without being sent. Its method is POST and its JSON-encoded body represents the invented topic and minutes. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For build json post requests deliberately in an after-CCA practice planner, start with the code expression responsible for the result: The server still owns validation, authorisation and the meaning of duplicate writes. A syntactically correct JSON body is not a grant to submit it anywhere. The controlled topic is ‘Punggol eco-notes’ and the mock count is 14. A POST may change server state. Build and inspect a Request object locally instead of posting fictional test records to unrelated services. In this case the returned keys [‘method’, ‘media’, ‘body’] are the evidence to inspect, not a claim that a real website is available. Ask whether the structure remains valid when the number of records doubles..

Check the boundary. First substitute topic “Art & Coding” for ‘Punggol eco-notes’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this build json post requests deliberately case in an after-CCA practice planner, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. When the result surprises the learner, keep the counterexample in the practice notes. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: build json post requests deliberately — a school-holiday project notebook

A pupil builds a little a school-holiday project notebook and wants to understand build json post requests deliberately. With topic ‘Science & Art’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is when an api expects json, use json.stringify for the body and identify the representation with the appropriate content-type.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=6;
const topic="Science & Art";
const data={topic,minutes:count};const r=new Request('https://practice.invalid/activities',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});const body=JSON.parse(await r.text());const result={method:r.method,media:r.headers.get('content-type'),body};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For build json post requests deliberately in a school-holiday project notebook, with the hypothetical ‘Science & Art’ topic and count 6, the independently executed Node.js Web API test prints {“method”:”POST”,”media”:”application/json”,”body”:{“topic”:”Science & Art”,”minutes”:6}}. Its observable properties are specific: A new Request is inspected without being sent. Its method is POST and its JSON-encoded body represents the invented topic and minutes. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For build json post requests deliberately in a school-holiday project notebook, start with the code expression responsible for the result: The server still owns validation, authorisation and the meaning of duplicate writes. A syntactically correct JSON body is not a grant to submit it anywhere. The controlled topic is ‘Science & Art’ and the mock count is 6. A POST may change server state. Build and inspect a Request object locally instead of posting fictional test records to unrelated services. In this case the returned keys [‘method’, ‘media’, ‘body’] are the evidence to inspect, not a claim that a real website is available. Start by identifying the unit of observation, then apply only the rule relevant to that unit..

Check the boundary. Now replace the invented count 6 with 11, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this build json post requests deliberately case in a school-holiday project notebook, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Treat a version-dependent result as a prompt to consult the current official manual. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: build json post requests deliberately — a mock fundraising spreadsheet

The make-believe records for a mock fundraising spreadsheet contain 18 observations under topic ‘Science & Art’. A friend says the program has worked because the console displays something. Test build json post requests deliberately: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is when an api expects json, use json.stringify for the body and identify the representation with the appropriate content-type.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=18;
const topic="Science & Art";
const data={topic,minutes:count};const r=new Request('https://practice.invalid/activities',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});const body=JSON.parse(await r.text());const result={method:r.method,media:r.headers.get('content-type'),body};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For build json post requests deliberately in a mock fundraising spreadsheet, with the hypothetical ‘Science & Art’ topic and count 18, the independently executed Node.js Web API test prints {“method”:”POST”,”media”:”application/json”,”body”:{“topic”:”Science & Art”,”minutes”:18}}. Its observable properties are specific: A new Request is inspected without being sent. Its method is POST and its JSON-encoded body represents the invented topic and minutes. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For build json post requests deliberately in a mock fundraising spreadsheet, start with the code expression responsible for the result: The server still owns validation, authorisation and the meaning of duplicate writes. A syntactically correct JSON body is not a grant to submit it anywhere. The controlled topic is ‘Science & Art’ and the mock count is 18. A POST may change server state. Build and inspect a Request object locally instead of posting fictional test records to unrelated services. In this case the returned keys [‘method’, ‘media’, ‘body’] are the evidence to inspect, not a claim that a real website is available. Compare the desired answer with an alternative that looks similar but measures something else..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a mock fundraising spreadsheet, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this build json post requests deliberately case in a mock fundraising spreadsheet, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. This is a proposed home exercise rather than a service or school claim. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: build json post requests deliberately — a toy digital noticeboard

After a shared family activity around a toy digital noticeboard, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Math + sketches’ and the invented integer 10. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is when an api expects json, use json.stringify for the body and identify the representation with the appropriate content-type.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=10;
const topic="Math + sketches";
const data={topic,minutes:count};const r=new Request('https://practice.invalid/activities',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});const body=JSON.parse(await r.text());const result={method:r.method,media:r.headers.get('content-type'),body};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For build json post requests deliberately in a toy digital noticeboard, with the hypothetical ‘Math + sketches’ topic and count 10, the independently executed Node.js Web API test prints {“method”:”POST”,”media”:”application/json”,”body”:{“topic”:”Math + sketches”,”minutes”:10}}. Its observable properties are specific: A new Request is inspected without being sent. Its method is POST and its JSON-encoded body represents the invented topic and minutes. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For build json post requests deliberately in a toy digital noticeboard, start with the code expression responsible for the result: The server still owns validation, authorisation and the meaning of duplicate writes. A syntactically correct JSON body is not a grant to submit it anywhere. The controlled topic is ‘Math + sketches’ and the mock count is 10. A POST may change server state. Build and inspect a Request object locally instead of posting fictional test records to unrelated services. In this case the returned keys [‘method’, ‘media’, ‘body’] are the evidence to inspect, not a claim that a real website is available. Cross-check with an independent hand calculation using the smallest workable values..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “writing a javascript object directly into request body and assuming it becomes json.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this build json post requests deliberately case in a toy digital noticeboard, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A useful parent prompt is to request a prediction, not a memorised command. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe build json post requests deliberately in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Inspect a new Request without sending a network call. Treat a version-dependent result as a prompt to consult the current official manual.

CHAPTER 11 OF 20 · Back to contents

11. Understand HTTP headers and credentials separately

Start with the answer: An Authorization or other sensitive header must follow the server contract; CORS and browser credential rules are separate concerns.

A toy Request can show a harmless made-up header, but pupils should never paste real account tokens into public code, websites or screenshots.

Common tempting error: Assuming that adding a header makes an endpoint accessible regardless of server policy.

Diagnostic for a parent or project partner: Who is authorised to receive the request and where would its credentials be stored?

Lab 1: understand http headers and credentials separately — a school-holiday project notebook

For a fictional family a school-holiday project notebook, the response is delayed but arrives intact. The topic is ‘Coastal habitats?’ and the controlled fixture uses count 4. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is an authorization or other sensitive header must follow the server contract; cors and browser credential rules are separate concerns.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=4;
const topic="Coastal habitats?";
const r=new Request('https://practice.invalid/activities',{headers:{'X-Practice-Tag':'fictional-'+count}});const result={method:r.method,practiceHeader:r.headers.get('x-practice-tag'),hasAuthorization:r.headers.has('authorization')};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For understand http headers and credentials separately in a school-holiday project notebook, with the hypothetical ‘Coastal habitats?’ topic and count 4, the independently executed Node.js Web API test prints {“method”:”GET”,”practiceHeader”:”fictional-4″,”hasAuthorization”:false}. Its observable properties are specific: A harmless practice header is visible in an unsent Request; the example deliberately includes no Authorization secret or personal data. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For understand http headers and credentials separately in a school-holiday project notebook, start with the code expression responsible for the result: Server acceptance, CORS permission and authentication decisions are not established by this local Request construction. The controlled topic is ‘Coastal habitats?’ and the mock count is 4. A toy Request can show a harmless made-up header, but pupils should never paste real account tokens into public code, websites or screenshots. In this case the returned keys [‘method’, ‘practiceHeader’, ‘hasAuthorization’] are the evidence to inspect, not a claim that a real website is available. Write down the unsuccessful interpretation and explain why it fails..

Check the boundary. First substitute topic “Art & Coding” for ‘Coastal habitats?’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this understand http headers and credentials separately case in a school-holiday project notebook, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The next step should be one small controlled variation, not ten simultaneous edits. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: understand http headers and credentials separately — a made-up quiz analysis

A pupil builds a little a made-up quiz analysis and wants to understand understand http headers and credentials separately. With topic ‘Punggol eco-notes’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is an authorization or other sensitive header must follow the server contract; cors and browser credential rules are separate concerns.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=13;
const topic="Punggol eco-notes";
const r=new Request('https://practice.invalid/activities',{headers:{'X-Practice-Tag':'fictional-'+count}});const result={method:r.method,practiceHeader:r.headers.get('x-practice-tag'),hasAuthorization:r.headers.has('authorization')};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For understand http headers and credentials separately in a made-up quiz analysis, with the hypothetical ‘Punggol eco-notes’ topic and count 13, the independently executed Node.js Web API test prints {“method”:”GET”,”practiceHeader”:”fictional-13″,”hasAuthorization”:false}. Its observable properties are specific: A harmless practice header is visible in an unsent Request; the example deliberately includes no Authorization secret or personal data. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For understand http headers and credentials separately in a made-up quiz analysis, start with the code expression responsible for the result: Server acceptance, CORS permission and authentication decisions are not established by this local Request construction. The controlled topic is ‘Punggol eco-notes’ and the mock count is 13. A toy Request can show a harmless made-up header, but pupils should never paste real account tokens into public code, websites or screenshots. In this case the returned keys [‘method’, ‘practiceHeader’, ‘hasAuthorization’] are the evidence to inspect, not a claim that a real website is available. Draw a miniature table and count the rows before calculating any summary..

Check the boundary. Now replace the invented count 13 with 18, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this understand http headers and credentials separately case in a made-up quiz analysis, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A clear explanation is more valuable than guessing an answer from the display. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: understand http headers and credentials separately — a toy digital noticeboard

The make-believe records for a toy digital noticeboard contain 8 observations under topic ‘Punggol eco-notes’. A friend says the program has worked because the console displays something. Test understand http headers and credentials separately: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is an authorization or other sensitive header must follow the server contract; cors and browser credential rules are separate concerns.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=8;
const topic="Punggol eco-notes";
const r=new Request('https://practice.invalid/activities',{headers:{'X-Practice-Tag':'fictional-'+count}});const result={method:r.method,practiceHeader:r.headers.get('x-practice-tag'),hasAuthorization:r.headers.has('authorization')};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For understand http headers and credentials separately in a toy digital noticeboard, with the hypothetical ‘Punggol eco-notes’ topic and count 8, the independently executed Node.js Web API test prints {“method”:”GET”,”practiceHeader”:”fictional-8″,”hasAuthorization”:false}. Its observable properties are specific: A harmless practice header is visible in an unsent Request; the example deliberately includes no Authorization secret or personal data. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For understand http headers and credentials separately in a toy digital noticeboard, start with the code expression responsible for the result: Server acceptance, CORS permission and authentication decisions are not established by this local Request construction. The controlled topic is ‘Punggol eco-notes’ and the mock count is 8. A toy Request can show a harmless made-up header, but pupils should never paste real account tokens into public code, websites or screenshots. In this case the returned keys [‘method’, ‘practiceHeader’, ‘hasAuthorization’] are the evidence to inspect, not a claim that a real website is available. Keep the input unchanged while adjusting a single condition..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a toy digital noticeboard, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this understand http headers and credentials separately case in a toy digital noticeboard, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. No real pupil information is needed; the test data are deliberately imaginary. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: understand http headers and credentials separately — a family revision tracker

After a shared family activity around a family revision tracker, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Science & Art’ and the invented integer 17. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is an authorization or other sensitive header must follow the server contract; cors and browser credential rules are separate concerns.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=17;
const topic="Science & Art";
const r=new Request('https://practice.invalid/activities',{headers:{'X-Practice-Tag':'fictional-'+count}});const result={method:r.method,practiceHeader:r.headers.get('x-practice-tag'),hasAuthorization:r.headers.has('authorization')};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For understand http headers and credentials separately in a family revision tracker, with the hypothetical ‘Science & Art’ topic and count 17, the independently executed Node.js Web API test prints {“method”:”GET”,”practiceHeader”:”fictional-17″,”hasAuthorization”:false}. Its observable properties are specific: A harmless practice header is visible in an unsent Request; the example deliberately includes no Authorization secret or personal data. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For understand http headers and credentials separately in a family revision tracker, start with the code expression responsible for the result: Server acceptance, CORS permission and authentication decisions are not established by this local Request construction. The controlled topic is ‘Science & Art’ and the mock count is 17. A toy Request can show a harmless made-up header, but pupils should never paste real account tokens into public code, websites or screenshots. In this case the returned keys [‘method’, ‘practiceHeader’, ‘hasAuthorization’] are the evidence to inspect, not a claim that a real website is available. Predict the behaviour before running a test; the difference between prediction and result is the learning target..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “assuming that adding a header makes an endpoint accessible regardless of server policy.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this understand http headers and credentials separately case in a family revision tracker, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. When the result surprises the learner, keep the counterexample in the practice notes. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe understand http headers and credentials separately in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Use a harmless test token and explain the policy boundary, not a bypass. Save the example so the learner can rerun it with a fresh number next week.

CHAPTER 12 OF 20 · Back to contents

12. Cancel a stale request with AbortController

Start with the answer: An AbortController signal can cancel supported fetch work; cancellation must be labelled differently from an empty result.

For example, a family coding exercise may search repeatedly while a learner types. The previous request may be obsolete and should not overwrite a newer choice.

Common tempting error: Reporting cancelled work as an HTTP 404 or zero matching records.

Diagnostic for a parent or project partner: Was the operation cancelled intentionally or did a server return a result?

Lab 1: cancel a stale request with abortcontroller — a made-up quiz analysis

For a fictional family a made-up quiz analysis, the response is delayed but arrives intact. The topic is ‘Math + sketches’ and the controlled fixture uses count 11. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is an abortcontroller signal can cancel supported fetch work; cancellation must be labelled differently from an empty result.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=11;
const topic="Math + sketches";
const controller=new AbortController();const before=controller.signal.aborted;controller.abort();const result={before,after:controller.signal.aborted,reasonName:controller.signal.reason?.name||typeof controller.signal.reason};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For cancel a stale request with abortcontroller in a made-up quiz analysis, with the hypothetical ‘Math + sketches’ topic and count 11, the independently executed Node.js Web API test prints {“before”:false,”after”:true,”reasonName”:”AbortError”}. Its observable properties are specific: A locally created signal changes from not aborted to aborted after controller.abort(). No network request is necessary to examine the cancellation state. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For cancel a stale request with abortcontroller in a made-up quiz analysis, start with the code expression responsible for the result: Actual cancellation timing also depends on request and body-stream stages. Cancellation must not be reported as proof of an empty data set. The controlled topic is ‘Math + sketches’ and the mock count is 11. For example, a family coding exercise may search repeatedly while a learner types. The previous request may be obsolete and should not overwrite a newer choice. In this case the returned keys [‘before’, ‘after’, ‘reasonName’] are the evidence to inspect, not a claim that a real website is available. Carry the result back to the family’s original decision, without claiming more than the data support..

Check the boundary. First substitute topic “Art & Coding” for ‘Math + sketches’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this cancel a stale request with abortcontroller case in a made-up quiz analysis, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Save the example so the learner can rerun it with a fresh number next week. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: cancel a stale request with abortcontroller — a weather-observation practice sheet

A pupil builds a little a weather-observation practice sheet and wants to understand cancel a stale request with abortcontroller. With topic ‘Coastal habitats?’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is an abortcontroller signal can cancel supported fetch work; cancellation must be labelled differently from an empty result.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=3;
const topic="Coastal habitats?";
const controller=new AbortController();const before=controller.signal.aborted;controller.abort();const result={before,after:controller.signal.aborted,reasonName:controller.signal.reason?.name||typeof controller.signal.reason};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For cancel a stale request with abortcontroller in a weather-observation practice sheet, with the hypothetical ‘Coastal habitats?’ topic and count 3, the independently executed Node.js Web API test prints {“before”:false,”after”:true,”reasonName”:”AbortError”}. Its observable properties are specific: A locally created signal changes from not aborted to aborted after controller.abort(). No network request is necessary to examine the cancellation state. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For cancel a stale request with abortcontroller in a weather-observation practice sheet, start with the code expression responsible for the result: Actual cancellation timing also depends on request and body-stream stages. Cancellation must not be reported as proof of an empty data set. The controlled topic is ‘Coastal habitats?’ and the mock count is 3. For example, a family coding exercise may search repeatedly while a learner types. The previous request may be obsolete and should not overwrite a newer choice. In this case the returned keys [‘before’, ‘after’, ‘reasonName’] are the evidence to inspect, not a claim that a real website is available. Explain the result in ordinary language before trusting a convenient display..

Check the boundary. Now replace the invented count 3 with 8, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this cancel a stale request with abortcontroller case in a weather-observation practice sheet, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. This is a proposed home exercise rather than a service or school claim. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: cancel a stale request with abortcontroller — a family revision tracker

The make-believe records for a family revision tracker contain 15 observations under topic ‘Coastal habitats?’. A friend says the program has worked because the console displays something. Test cancel a stale request with abortcontroller: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is an abortcontroller signal can cancel supported fetch work; cancellation must be labelled differently from an empty result.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=15;
const topic="Coastal habitats?";
const controller=new AbortController();const before=controller.signal.aborted;controller.abort();const result={before,after:controller.signal.aborted,reasonName:controller.signal.reason?.name||typeof controller.signal.reason};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For cancel a stale request with abortcontroller in a family revision tracker, with the hypothetical ‘Coastal habitats?’ topic and count 15, the independently executed Node.js Web API test prints {“before”:false,”after”:true,”reasonName”:”AbortError”}. Its observable properties are specific: A locally created signal changes from not aborted to aborted after controller.abort(). No network request is necessary to examine the cancellation state. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For cancel a stale request with abortcontroller in a family revision tracker, start with the code expression responsible for the result: Actual cancellation timing also depends on request and body-stream stages. Cancellation must not be reported as proof of an empty data set. The controlled topic is ‘Coastal habitats?’ and the mock count is 15. For example, a family coding exercise may search repeatedly while a learner types. The previous request may be obsolete and should not overwrite a newer choice. In this case the returned keys [‘before’, ‘after’, ‘reasonName’] are the evidence to inspect, not a claim that a real website is available. Name which records enter the calculation and which stay outside..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a family revision tracker, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this cancel a stale request with abortcontroller case in a family revision tracker, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The goal is not to finish a huge worksheet; it is to explain one reliable decision. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: cancel a stale request with abortcontroller — a small library-book experiment

After a shared family activity around a small library-book experiment, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Punggol eco-notes’ and the invented integer 7. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is an abortcontroller signal can cancel supported fetch work; cancellation must be labelled differently from an empty result.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=7;
const topic="Punggol eco-notes";
const controller=new AbortController();const before=controller.signal.aborted;controller.abort();const result={before,after:controller.signal.aborted,reasonName:controller.signal.reason?.name||typeof controller.signal.reason};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For cancel a stale request with abortcontroller in a small library-book experiment, with the hypothetical ‘Punggol eco-notes’ topic and count 7, the independently executed Node.js Web API test prints {“before”:false,”after”:true,”reasonName”:”AbortError”}. Its observable properties are specific: A locally created signal changes from not aborted to aborted after controller.abort(). No network request is necessary to examine the cancellation state. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For cancel a stale request with abortcontroller in a small library-book experiment, start with the code expression responsible for the result: Actual cancellation timing also depends on request and body-stream stages. Cancellation must not be reported as proof of an empty data set. The controlled topic is ‘Punggol eco-notes’ and the mock count is 7. For example, a family coding exercise may search repeatedly while a learner types. The previous request may be obsolete and should not overwrite a newer choice. In this case the returned keys [‘before’, ‘after’, ‘reasonName’] are the evidence to inspect, not a claim that a real website is available. Ask whether the structure remains valid when the number of records doubles..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “reporting cancelled work as an http 404 or zero matching records.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this cancel a stale request with abortcontroller case in a small library-book experiment, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The next step should be one small controlled variation, not ten simultaneous edits. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe cancel a stale request with abortcontroller in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Construct an already-aborted signal and observe its state without network access. A clear explanation is more valuable than guessing an answer from the display.

CHAPTER 13 OF 20 · Back to contents

13. Prevent older responses overwriting newer choices

Start with the answer: A sequence token or equivalent latest-request guard helps keep stale async completion from changing the displayed answer.

Even when cancellation is available, application state should be updated only by the response corresponding to the current intent. Reversed completion order is a good deterministic test.

Common tempting error: Assuming requests finish in the order they started.

Diagnostic for a parent or project partner: Which query did the user make most recently?

Lab 1: prevent older responses overwriting newer choices — a weather-observation practice sheet

For a fictional family a weather-observation practice sheet, the response is delayed but arrives intact. The topic is ‘Science & Art’ and the controlled fixture uses count 18. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a sequence token or equivalent latest-request guard helps keep stale async completion from changing the displayed answer.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=18;
const topic="Science & Art";
let latest=0;let screen='idle';const first=++latest;const second=++latest;const arrivals=[{id:second,value:topic+' new'},{id:first,value:topic+' old'}];for(const a of arrivals){if(a.id===latest)screen=a.value;}const result={first,second,screen,staleIgnored:screen!==topic+' old'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For prevent older responses overwriting newer choices in a weather-observation practice sheet, with the hypothetical ‘Science & Art’ topic and count 18, the independently executed Node.js Web API test prints {“first”:1,”second”:2,”screen”:”Science & Art new”,”staleIgnored”:true}. Its observable properties are specific: The second request is logically newer but completes first. The token guard accepts its value and ignores the later completion of the older request. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For prevent older responses overwriting newer choices in a weather-observation practice sheet, start with the code expression responsible for the result: Actual network cancellation is separate. UI state must preserve the user’s newest expressed intent. The controlled topic is ‘Science & Art’ and the mock count is 18. Even when cancellation is available, application state should be updated only by the response corresponding to the current intent. Reversed completion order is a good deterministic test. In this case the returned keys [‘first’, ‘second’, ‘screen’, ‘staleIgnored’] are the evidence to inspect, not a claim that a real website is available. Start by identifying the unit of observation, then apply only the rule relevant to that unit..

Check the boundary. First substitute topic “Art & Coding” for ‘Science & Art’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this prevent older responses overwriting newer choices case in a weather-observation practice sheet, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Try this on a small, invented table before using any real schoolwork. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: prevent older responses overwriting newer choices — a shared family study calendar

A pupil builds a little a shared family study calendar and wants to understand prevent older responses overwriting newer choices. With topic ‘Math + sketches’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a sequence token or equivalent latest-request guard helps keep stale async completion from changing the displayed answer.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=10;
const topic="Math + sketches";
let latest=0;let screen='idle';const first=++latest;const second=++latest;const arrivals=[{id:second,value:topic+' new'},{id:first,value:topic+' old'}];for(const a of arrivals){if(a.id===latest)screen=a.value;}const result={first,second,screen,staleIgnored:screen!==topic+' old'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For prevent older responses overwriting newer choices in a shared family study calendar, with the hypothetical ‘Math + sketches’ topic and count 10, the independently executed Node.js Web API test prints {“first”:1,”second”:2,”screen”:”Math + sketches new”,”staleIgnored”:true}. Its observable properties are specific: The second request is logically newer but completes first. The token guard accepts its value and ignores the later completion of the older request. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For prevent older responses overwriting newer choices in a shared family study calendar, start with the code expression responsible for the result: Actual network cancellation is separate. UI state must preserve the user’s newest expressed intent. The controlled topic is ‘Math + sketches’ and the mock count is 10. Even when cancellation is available, application state should be updated only by the response corresponding to the current intent. Reversed completion order is a good deterministic test. In this case the returned keys [‘first’, ‘second’, ‘screen’, ‘staleIgnored’] are the evidence to inspect, not a claim that a real website is available. Check the case that would make a tempting shortcut wrong..

Check the boundary. Now replace the invented count 10 with 15, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this prevent older responses overwriting newer choices case in a shared family study calendar, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. No real pupil information is needed; the test data are deliberately imaginary. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: prevent older responses overwriting newer choices — a small library-book experiment

The make-believe records for a small library-book experiment contain 5 observations under topic ‘Math + sketches’. A friend says the program has worked because the console displays something. Test prevent older responses overwriting newer choices: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a sequence token or equivalent latest-request guard helps keep stale async completion from changing the displayed answer.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=5;
const topic="Math + sketches";
let latest=0;let screen='idle';const first=++latest;const second=++latest;const arrivals=[{id:second,value:topic+' new'},{id:first,value:topic+' old'}];for(const a of arrivals){if(a.id===latest)screen=a.value;}const result={first,second,screen,staleIgnored:screen!==topic+' old'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For prevent older responses overwriting newer choices in a small library-book experiment, with the hypothetical ‘Math + sketches’ topic and count 5, the independently executed Node.js Web API test prints {“first”:1,”second”:2,”screen”:”Math + sketches new”,”staleIgnored”:true}. Its observable properties are specific: The second request is logically newer but completes first. The token guard accepts its value and ignores the later completion of the older request. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For prevent older responses overwriting newer choices in a small library-book experiment, start with the code expression responsible for the result: Actual network cancellation is separate. UI state must preserve the user’s newest expressed intent. The controlled topic is ‘Math + sketches’ and the mock count is 5. Even when cancellation is available, application state should be updated only by the response corresponding to the current intent. Reversed completion order is a good deterministic test. In this case the returned keys [‘first’, ‘second’, ‘screen’, ‘staleIgnored’] are the evidence to inspect, not a claim that a real website is available. Cross-check with an independent hand calculation using the smallest workable values..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a small library-book experiment, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this prevent older responses overwriting newer choices case in a small library-book experiment, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Independent checking beats a polished screen that nobody can explain. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: prevent older responses overwriting newer choices — a fictional student coding challenge

After a shared family activity around a fictional student coding challenge, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Coastal habitats?’ and the invented integer 14. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a sequence token or equivalent latest-request guard helps keep stale async completion from changing the displayed answer.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=14;
const topic="Coastal habitats?";
let latest=0;let screen='idle';const first=++latest;const second=++latest;const arrivals=[{id:second,value:topic+' new'},{id:first,value:topic+' old'}];for(const a of arrivals){if(a.id===latest)screen=a.value;}const result={first,second,screen,staleIgnored:screen!==topic+' old'};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For prevent older responses overwriting newer choices in a fictional student coding challenge, with the hypothetical ‘Coastal habitats?’ topic and count 14, the independently executed Node.js Web API test prints {“first”:1,”second”:2,”screen”:”Coastal habitats? new”,”staleIgnored”:true}. Its observable properties are specific: The second request is logically newer but completes first. The token guard accepts its value and ignores the later completion of the older request. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For prevent older responses overwriting newer choices in a fictional student coding challenge, start with the code expression responsible for the result: Actual network cancellation is separate. UI state must preserve the user’s newest expressed intent. The controlled topic is ‘Coastal habitats?’ and the mock count is 14. Even when cancellation is available, application state should be updated only by the response corresponding to the current intent. Reversed completion order is a good deterministic test. In this case the returned keys [‘first’, ‘second’, ‘screen’, ‘staleIgnored’] are the evidence to inspect, not a claim that a real website is available. Write down the unsuccessful interpretation and explain why it fails..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “assuming requests finish in the order they started.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this prevent older responses overwriting newer choices case in a fictional student coding challenge, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Save the example so the learner can rerun it with a fresh number next week. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe prevent older responses overwriting newer choices in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Resolve two hypothetical promises in reverse order and verify which result is retained. Try this on a small, invented table before using any real schoolwork.

CHAPTER 14 OF 20 · Back to contents

14. Handle Promise.all failure explicitly

Start with the answer: Promise.all rejects when any constituent promise rejects, although individual fetch HTTP error responses do not automatically reject.

A parallel dashboard may want all sections or may want partial success. The choice is about user meaning, not which Promise helper appears shorter.

Common tempting error: Believing Promise.all will reject just because one valid Response has status 404.

Diagnostic for a parent or project partner: Does the application require every result to be usable before showing anything?

Lab 1: handle promise.all failure explicitly — a shared family study calendar

For a fictional family a shared family study calendar, the response is delayed but arrives intact. The topic is ‘Punggol eco-notes’ and the controlled fixture uses count 8. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is promise.all rejects when any constituent promise rejects, although individual fetch http error responses do not automatically reject.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=8;
const topic="Punggol eco-notes";
const tasks=[Promise.resolve(new Response('ok',{status:200})),Promise.resolve(new Response('',{status:404})),Promise.resolve(7)];let all;try{const r=await Promise.all(tasks);all={state:'fulfilled',secondStatus:r[1].status};}catch(e){all={state:'rejected',message:e.message};}const settled=await Promise.allSettled(tasks);const result={all,states:settled.map(x=>x.status)};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For handle promise.all failure explicitly in a shared family study calendar, with the hypothetical ‘Punggol eco-notes’ topic and count 8, the independently executed Node.js Web API test prints {“all”:{“state”:”fulfilled”,”secondStatus”:404},”states”:[“fulfilled”,”fulfilled”,”fulfilled”]}. Its observable properties are specific: This case uses three synthetic promises. A 404 Response still fulfils; an actual rejected promise causes Promise.all to reject. allSettled preserves the status of each individual promise. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For handle promise.all failure explicitly in a shared family study calendar, start with the code expression responsible for the result: Choose fail-fast or partial-success behaviour according to whether the family project can use only one section of a report. The controlled topic is ‘Punggol eco-notes’ and the mock count is 8. A parallel dashboard may want all sections or may want partial success. The choice is about user meaning, not which Promise helper appears shorter. In this case the returned keys [‘all’, ‘states’] are the evidence to inspect, not a claim that a real website is available. Draw a miniature table and count the rows before calculating any summary..

Check the boundary. First substitute topic “Art & Coding” for ‘Punggol eco-notes’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this handle promise.all failure explicitly case in a shared family study calendar, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A Punggol family can practise this with fictional numbers after dinner or over a weekend. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: handle promise.all failure explicitly — a weekend reading journal

A pupil builds a little a weekend reading journal and wants to understand handle promise.all failure explicitly. With topic ‘Science & Art’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is promise.all rejects when any constituent promise rejects, although individual fetch http error responses do not automatically reject.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=17;
const topic="Science & Art";
const tasks=[Promise.resolve(new Response('ok',{status:200})),Promise.reject(new Error('offline')),Promise.resolve(7)];let all;try{const r=await Promise.all(tasks);all={state:'fulfilled',secondStatus:r[1].status};}catch(e){all={state:'rejected',message:e.message};}const settled=await Promise.allSettled(tasks);const result={all,states:settled.map(x=>x.status)};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For handle promise.all failure explicitly in a weekend reading journal, with the hypothetical ‘Science & Art’ topic and count 17, the independently executed Node.js Web API test prints {“all”:{“state”:”rejected”,”message”:”offline”},”states”:[“fulfilled”,”rejected”,”fulfilled”]}. Its observable properties are specific: This case uses three synthetic promises. A 404 Response still fulfils; an actual rejected promise causes Promise.all to reject. allSettled preserves the status of each individual promise. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For handle promise.all failure explicitly in a weekend reading journal, start with the code expression responsible for the result: Choose fail-fast or partial-success behaviour according to whether the family project can use only one section of a report. The controlled topic is ‘Science & Art’ and the mock count is 17. A parallel dashboard may want all sections or may want partial success. The choice is about user meaning, not which Promise helper appears shorter. In this case the returned keys [‘all’, ‘states’] are the evidence to inspect, not a claim that a real website is available. Compare the desired answer with an alternative that looks similar but measures something else..

Check the boundary. Now replace the invented count 17 with 22, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this handle promise.all failure explicitly case in a weekend reading journal, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The goal is not to finish a huge worksheet; it is to explain one reliable decision. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: handle promise.all failure explicitly — a fictional student coding challenge

The make-believe records for a fictional student coding challenge contain 12 observations under topic ‘Science & Art’. A friend says the program has worked because the console displays something. Test handle promise.all failure explicitly: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is promise.all rejects when any constituent promise rejects, although individual fetch http error responses do not automatically reject.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=12;
const topic="Science & Art";
const tasks=[Promise.resolve(new Response('ok',{status:200})),Promise.resolve(new Response('',{status:404})),Promise.resolve(7)];let all;try{const r=await Promise.all(tasks);all={state:'fulfilled',secondStatus:r[1].status};}catch(e){all={state:'rejected',message:e.message};}const settled=await Promise.allSettled(tasks);const result={all,states:settled.map(x=>x.status)};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For handle promise.all failure explicitly in a fictional student coding challenge, with the hypothetical ‘Science & Art’ topic and count 12, the independently executed Node.js Web API test prints {“all”:{“state”:”fulfilled”,”secondStatus”:404},”states”:[“fulfilled”,”fulfilled”,”fulfilled”]}. Its observable properties are specific: This case uses three synthetic promises. A 404 Response still fulfils; an actual rejected promise causes Promise.all to reject. allSettled preserves the status of each individual promise. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For handle promise.all failure explicitly in a fictional student coding challenge, start with the code expression responsible for the result: Choose fail-fast or partial-success behaviour according to whether the family project can use only one section of a report. The controlled topic is ‘Science & Art’ and the mock count is 12. A parallel dashboard may want all sections or may want partial success. The choice is about user meaning, not which Promise helper appears shorter. In this case the returned keys [‘all’, ‘states’] are the evidence to inspect, not a claim that a real website is available. Predict the behaviour before running a test; the difference between prediction and result is the learning target..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a fictional student coding challenge, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this handle promise.all failure explicitly case in a fictional student coding challenge, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Treat a version-dependent result as a prompt to consult the current official manual. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: handle promise.all failure explicitly — a mock group presentation tracker

After a shared family activity around a mock group presentation tracker, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Math + sketches’ and the invented integer 4. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is promise.all rejects when any constituent promise rejects, although individual fetch http error responses do not automatically reject.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=4;
const topic="Math + sketches";
const tasks=[Promise.resolve(new Response('ok',{status:200})),Promise.reject(new Error('offline')),Promise.resolve(7)];let all;try{const r=await Promise.all(tasks);all={state:'fulfilled',secondStatus:r[1].status};}catch(e){all={state:'rejected',message:e.message};}const settled=await Promise.allSettled(tasks);const result={all,states:settled.map(x=>x.status)};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For handle promise.all failure explicitly in a mock group presentation tracker, with the hypothetical ‘Math + sketches’ topic and count 4, the independently executed Node.js Web API test prints {“all”:{“state”:”rejected”,”message”:”offline”},”states”:[“fulfilled”,”rejected”,”fulfilled”]}. Its observable properties are specific: This case uses three synthetic promises. A 404 Response still fulfils; an actual rejected promise causes Promise.all to reject. allSettled preserves the status of each individual promise. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For handle promise.all failure explicitly in a mock group presentation tracker, start with the code expression responsible for the result: Choose fail-fast or partial-success behaviour according to whether the family project can use only one section of a report. The controlled topic is ‘Math + sketches’ and the mock count is 4. A parallel dashboard may want all sections or may want partial success. The choice is about user meaning, not which Promise helper appears shorter. In this case the returned keys [‘all’, ‘states’] are the evidence to inspect, not a claim that a real website is available. Carry the result back to the family’s original decision, without claiming more than the data support..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “believing promise.all will reject just because one valid response has status 404.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this handle promise.all failure explicitly case in a mock group presentation tracker, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Try this on a small, invented table before using any real schoolwork. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe handle promise.all failure explicitly in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Compare Promise.all with allSettled on three fully controlled outcomes. This is a proposed home exercise rather than a service or school claim.

CHAPTER 15 OF 20 · Back to contents

15. Retry cautiously and distinguish GET from POST

Start with the answer: Retrying an idempotent read may be reasonable under a documented bounded policy; blindly retrying a POST can duplicate an action.

A lost response does not prove that a write failed. Only the server can define deduplication and idempotency support for its endpoint.

Common tempting error: Using unlimited automatic retries on every HTTP method.

Diagnostic for a parent or project partner: Could the first attempt have changed server state before its acknowledgement was lost?

Lab 1: retry cautiously and distinguish get from post — a weekend reading journal

For a fictional family a weekend reading journal, the response is delayed but arrives intact. The topic is ‘Coastal habitats?’ and the controlled fixture uses count 15. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is retrying an idempotent read may be reasonable under a documented bounded policy; blindly retrying a post can duplicate an action.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=15;
const topic="Coastal habitats?";
const method='GET';const outcomes=[500,503,200];let made=0;let last=null;for(const status of outcomes){made++;last=status;if(status===200)break;if(method!=='GET')break;}const result={method,made,lastStatus:last,retried:made>1};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For retry cautiously and distinguish get from post in a weekend reading journal, with the hypothetical ‘Coastal habitats?’ topic and count 15, the independently executed Node.js Web API test prints {“method”:”GET”,”made”:3,”lastStatus”:200,”retried”:true}. Its observable properties are specific: The toy policy permits additional attempts only for the specified GET. For POST, it stops after the first simulated HTTP 500 because resubmission could duplicate a server-side change. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For retry cautiously and distinguish get from post in a weekend reading journal, start with the code expression responsible for the result: Real GETs can still have side effects in badly designed endpoints; a robust retry policy also needs bounded delays and the actual documented service contract. The controlled topic is ‘Coastal habitats?’ and the mock count is 15. A lost response does not prove that a write failed. Only the server can define deduplication and idempotency support for its endpoint. In this case the returned keys [‘method’, ‘made’, ‘lastStatus’, ‘retried’] are the evidence to inspect, not a claim that a real website is available. Explain the result in ordinary language before trusting a convenient display..

Check the boundary. First substitute topic “Art & Coding” for ‘Coastal habitats?’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this retry cautiously and distinguish get from post case in a weekend reading journal, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A useful parent prompt is to request a prediction, not a memorised command. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: retry cautiously and distinguish get from post — a simulated science-club project

A pupil builds a little a simulated science-club project and wants to understand retry cautiously and distinguish get from post. With topic ‘Punggol eco-notes’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is retrying an idempotent read may be reasonable under a documented bounded policy; blindly retrying a post can duplicate an action.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=7;
const topic="Punggol eco-notes";
const method='POST';const outcomes=[500,503,200];let made=0;let last=null;for(const status of outcomes){made++;last=status;if(status===200)break;if(method!=='GET')break;}const result={method,made,lastStatus:last,retried:made>1};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For retry cautiously and distinguish get from post in a simulated science-club project, with the hypothetical ‘Punggol eco-notes’ topic and count 7, the independently executed Node.js Web API test prints {“method”:”POST”,”made”:1,”lastStatus”:500,”retried”:false}. Its observable properties are specific: The toy policy permits additional attempts only for the specified GET. For POST, it stops after the first simulated HTTP 500 because resubmission could duplicate a server-side change. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For retry cautiously and distinguish get from post in a simulated science-club project, start with the code expression responsible for the result: Real GETs can still have side effects in badly designed endpoints; a robust retry policy also needs bounded delays and the actual documented service contract. The controlled topic is ‘Punggol eco-notes’ and the mock count is 7. A lost response does not prove that a write failed. Only the server can define deduplication and idempotency support for its endpoint. In this case the returned keys [‘method’, ‘made’, ‘lastStatus’, ‘retried’] are the evidence to inspect, not a claim that a real website is available. Keep the input unchanged while adjusting a single condition..

Check the boundary. Now replace the invented count 7 with 12, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this retry cautiously and distinguish get from post case in a simulated science-club project, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Independent checking beats a polished screen that nobody can explain. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: retry cautiously and distinguish get from post — a mock group presentation tracker

The make-believe records for a mock group presentation tracker contain 2 observations under topic ‘Punggol eco-notes’. A friend says the program has worked because the console displays something. Test retry cautiously and distinguish get from post: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is retrying an idempotent read may be reasonable under a documented bounded policy; blindly retrying a post can duplicate an action.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=2;
const topic="Punggol eco-notes";
const method='GET';const outcomes=[500,503,200];let made=0;let last=null;for(const status of outcomes){made++;last=status;if(status===200)break;if(method!=='GET')break;}const result={method,made,lastStatus:last,retried:made>1};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For retry cautiously and distinguish get from post in a mock group presentation tracker, with the hypothetical ‘Punggol eco-notes’ topic and count 2, the independently executed Node.js Web API test prints {“method”:”GET”,”made”:3,”lastStatus”:200,”retried”:true}. Its observable properties are specific: The toy policy permits additional attempts only for the specified GET. For POST, it stops after the first simulated HTTP 500 because resubmission could duplicate a server-side change. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For retry cautiously and distinguish get from post in a mock group presentation tracker, start with the code expression responsible for the result: Real GETs can still have side effects in badly designed endpoints; a robust retry policy also needs bounded delays and the actual documented service contract. The controlled topic is ‘Punggol eco-notes’ and the mock count is 2. A lost response does not prove that a write failed. Only the server can define deduplication and idempotency support for its endpoint. In this case the returned keys [‘method’, ‘made’, ‘lastStatus’, ‘retried’] are the evidence to inspect, not a claim that a real website is available. Ask whether the structure remains valid when the number of records doubles..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a mock group presentation tracker, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this retry cautiously and distinguish get from post case in a mock group presentation tracker, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A clear explanation is more valuable than guessing an answer from the display. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: retry cautiously and distinguish get from post — a volunteer-hours planning exercise

After a shared family activity around a volunteer-hours planning exercise, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Science & Art’ and the invented integer 11. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is retrying an idempotent read may be reasonable under a documented bounded policy; blindly retrying a post can duplicate an action.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=11;
const topic="Science & Art";
const method='POST';const outcomes=[500,503,200];let made=0;let last=null;for(const status of outcomes){made++;last=status;if(status===200)break;if(method!=='GET')break;}const result={method,made,lastStatus:last,retried:made>1};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For retry cautiously and distinguish get from post in a volunteer-hours planning exercise, with the hypothetical ‘Science & Art’ topic and count 11, the independently executed Node.js Web API test prints {“method”:”POST”,”made”:1,”lastStatus”:500,”retried”:false}. Its observable properties are specific: The toy policy permits additional attempts only for the specified GET. For POST, it stops after the first simulated HTTP 500 because resubmission could duplicate a server-side change. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For retry cautiously and distinguish get from post in a volunteer-hours planning exercise, start with the code expression responsible for the result: Real GETs can still have side effects in badly designed endpoints; a robust retry policy also needs bounded delays and the actual documented service contract. The controlled topic is ‘Science & Art’ and the mock count is 11. A lost response does not prove that a write failed. Only the server can define deduplication and idempotency support for its endpoint. In this case the returned keys [‘method’, ‘made’, ‘lastStatus’, ‘retried’] are the evidence to inspect, not a claim that a real website is available. Start by identifying the unit of observation, then apply only the rule relevant to that unit..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “using unlimited automatic retries on every http method.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this retry cautiously and distinguish get from post case in a volunteer-hours planning exercise, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A Punggol family can practise this with fictional numbers after dinner or over a weekend. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe retry cautiously and distinguish get from post in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Count toy attempts and say which ones could safely be tried again. A Punggol family can practise this with fictional numbers after dinner or over a weekend.

CHAPTER 16 OF 20 · Back to contents

16. Read Retry-After as advisory response metadata

Start with the answer: A 429 or 503 response may include Retry-After, but the client should interpret its syntax and application policy before scheduling work.

Numeric Retry-After represents seconds. HTTP dates are another valid form; a beginner exercise can focus on seconds and document date handling as a separate task.

Common tempting error: Treating the value as milliseconds or as a guarantee a retry will succeed.

Diagnostic for a parent or project partner: Does a delay hint apply here and is retrying this method even appropriate?

Lab 1: read retry-after as advisory response metadata — a simulated science-club project

For a fictional family a simulated science-club project, the response is delayed but arrives intact. The topic is ‘Math + sketches’ and the controlled fixture uses count 5. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a 429 or 503 response may include retry-after, but the client should interpret its syntax and application policy before scheduling work.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=5;
const topic="Math + sketches";
const r=new Response('',{status:429,headers:{'Retry-After':'1'}});const raw=r.headers.get('retry-after');const seconds=Number(raw);const result={status:r.status,raw,seconds,hintApplies:[429,503].includes(r.status)&&Number.isFinite(seconds)};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For read retry-after as advisory response metadata in a simulated science-club project, with the hypothetical ‘Math + sketches’ topic and count 5, the independently executed Node.js Web API test prints {“status”:429,”raw”:”1″,”seconds”:1,”hintApplies”:true}. Its observable properties are specific: An explicit Retry-After header reads 1 seconds in this numeric example; it is not a millisecond count. The policy checks that status 429 is one where the toy client might consult the hint. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For read retry-after as advisory response metadata in a simulated science-club project, start with the code expression responsible for the result: HTTP-date values need a different parser. A retry must also be safe for the operation and the service’s policy. The controlled topic is ‘Math + sketches’ and the mock count is 5. Numeric Retry-After represents seconds. HTTP dates are another valid form; a beginner exercise can focus on seconds and document date handling as a separate task. In this case the returned keys [‘status’, ‘raw’, ‘seconds’, ‘hintApplies’] are the evidence to inspect, not a claim that a real website is available. Check the case that would make a tempting shortcut wrong..

Check the boundary. First substitute topic “Art & Coding” for ‘Math + sketches’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this read retry-after as advisory response metadata case in a simulated science-club project, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. When the result surprises the learner, keep the counterexample in the practice notes. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: read retry-after as advisory response metadata — a recycled-materials tally

A pupil builds a little a recycled-materials tally and wants to understand read retry-after as advisory response metadata. With topic ‘Coastal habitats?’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a 429 or 503 response may include retry-after, but the client should interpret its syntax and application policy before scheduling work.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=14;
const topic="Coastal habitats?";
const r=new Response('',{status:503,headers:{'Retry-After':'5'}});const raw=r.headers.get('retry-after');const seconds=Number(raw);const result={status:r.status,raw,seconds,hintApplies:[429,503].includes(r.status)&&Number.isFinite(seconds)};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For read retry-after as advisory response metadata in a recycled-materials tally, with the hypothetical ‘Coastal habitats?’ topic and count 14, the independently executed Node.js Web API test prints {“status”:503,”raw”:”5″,”seconds”:5,”hintApplies”:true}. Its observable properties are specific: An explicit Retry-After header reads 5 seconds in this numeric example; it is not a millisecond count. The policy checks that status 503 is one where the toy client might consult the hint. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For read retry-after as advisory response metadata in a recycled-materials tally, start with the code expression responsible for the result: HTTP-date values need a different parser. A retry must also be safe for the operation and the service’s policy. The controlled topic is ‘Coastal habitats?’ and the mock count is 14. Numeric Retry-After represents seconds. HTTP dates are another valid form; a beginner exercise can focus on seconds and document date handling as a separate task. In this case the returned keys [‘status’, ‘raw’, ‘seconds’, ‘hintApplies’] are the evidence to inspect, not a claim that a real website is available. Name which records enter the calculation and which stay outside..

Check the boundary. Now replace the invented count 14 with 19, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this read retry-after as advisory response metadata case in a recycled-materials tally, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Treat a version-dependent result as a prompt to consult the current official manual. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: read retry-after as advisory response metadata — a volunteer-hours planning exercise

The make-believe records for a volunteer-hours planning exercise contain 9 observations under topic ‘Coastal habitats?’. A friend says the program has worked because the console displays something. Test read retry-after as advisory response metadata: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a 429 or 503 response may include retry-after, but the client should interpret its syntax and application policy before scheduling work.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=9;
const topic="Coastal habitats?";
const r=new Response('',{status:200,headers:{'Retry-After':'15'}});const raw=r.headers.get('retry-after');const seconds=Number(raw);const result={status:r.status,raw,seconds,hintApplies:[429,503].includes(r.status)&&Number.isFinite(seconds)};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For read retry-after as advisory response metadata in a volunteer-hours planning exercise, with the hypothetical ‘Coastal habitats?’ topic and count 9, the independently executed Node.js Web API test prints {“status”:200,”raw”:”15″,”seconds”:15,”hintApplies”:false}. Its observable properties are specific: An explicit Retry-After header reads 15 seconds in this numeric example; it is not a millisecond count. The policy checks that status 200 is one where the toy client might consult the hint. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For read retry-after as advisory response metadata in a volunteer-hours planning exercise, start with the code expression responsible for the result: HTTP-date values need a different parser. A retry must also be safe for the operation and the service’s policy. The controlled topic is ‘Coastal habitats?’ and the mock count is 9. Numeric Retry-After represents seconds. HTTP dates are another valid form; a beginner exercise can focus on seconds and document date handling as a separate task. In this case the returned keys [‘status’, ‘raw’, ‘seconds’, ‘hintApplies’] are the evidence to inspect, not a claim that a real website is available. Write down the unsuccessful interpretation and explain why it fails..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a volunteer-hours planning exercise, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this read retry-after as advisory response metadata case in a volunteer-hours planning exercise, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. This is a proposed home exercise rather than a service or school claim. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: read retry-after as advisory response metadata — a public-transport timing experiment

After a shared family activity around a public-transport timing experiment, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Punggol eco-notes’ and the invented integer 18. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a 429 or 503 response may include retry-after, but the client should interpret its syntax and application policy before scheduling work.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=18;
const topic="Punggol eco-notes";
const r=new Response('',{status:429,headers:{'Retry-After':'45'}});const raw=r.headers.get('retry-after');const seconds=Number(raw);const result={status:r.status,raw,seconds,hintApplies:[429,503].includes(r.status)&&Number.isFinite(seconds)};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For read retry-after as advisory response metadata in a public-transport timing experiment, with the hypothetical ‘Punggol eco-notes’ topic and count 18, the independently executed Node.js Web API test prints {“status”:429,”raw”:”45″,”seconds”:45,”hintApplies”:true}. Its observable properties are specific: An explicit Retry-After header reads 45 seconds in this numeric example; it is not a millisecond count. The policy checks that status 429 is one where the toy client might consult the hint. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For read retry-after as advisory response metadata in a public-transport timing experiment, start with the code expression responsible for the result: HTTP-date values need a different parser. A retry must also be safe for the operation and the service’s policy. The controlled topic is ‘Punggol eco-notes’ and the mock count is 18. Numeric Retry-After represents seconds. HTTP dates are another valid form; a beginner exercise can focus on seconds and document date handling as a separate task. In this case the returned keys [‘status’, ‘raw’, ‘seconds’, ‘hintApplies’] are the evidence to inspect, not a claim that a real website is available. Draw a miniature table and count the rows before calculating any summary..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “treating the value as milliseconds or as a guarantee a retry will succeed.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this read retry-after as advisory response metadata case in a public-transport timing experiment, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A useful parent prompt is to request a prediction, not a memorised command. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe read retry-after as advisory response metadata in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Parse a numeric mock header and compare its unit with a one-second interval. No real pupil information is needed; the test data are deliberately imaginary.

CHAPTER 17 OF 20 · Back to contents

17. Interpret redirects before reading data

Start with the answer: The response URL and redirected flag can reveal a followed redirect; a redirect is not necessarily a permission or security success.

Browsers usually follow redirects under the default fetch setting, but manual redirects and cross-origin constraints can behave differently. Test a mock Response.redirect separately.

Common tempting error: Concluding a redirect happened simply because a URL string contains a path change.

Diagnostic for a parent or project partner: Where did this response come from and was a redirect intentionally permitted?

Lab 1: interpret redirects before reading data — a recycled-materials tally

For a fictional family a recycled-materials tally, the response is delayed but arrives intact. The topic is ‘Science & Art’ and the controlled fixture uses count 12. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is the response url and redirected flag can reveal a followed redirect; a redirect is not necessarily a permission or security success.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=12;
const topic="Science & Art";
const r=Response.redirect('https://practice.invalid/new-path',301);const result={status:r.status,location:r.headers.get('location'),redirected:r.redirected};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For interpret redirects before reading data in a recycled-materials tally, with the hypothetical ‘Science & Art’ topic and count 12, the independently executed Node.js Web API test prints {“status”:301,”location”:”https://practice.invalid/new-path”,”redirected”:false}. Its observable properties are specific: An explicitly constructed redirect Response represents status 301 with a Location header. Its redirected property is not true, because the local object did not result from an actually followed redirect chain. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For interpret redirects before reading data in a recycled-materials tally, start with the code expression responsible for the result: Manual redirect handling in a browser may conceal cross-origin Location and return an opaque redirect, depending on fetch mode and constraints. The controlled topic is ‘Science & Art’ and the mock count is 12. Browsers usually follow redirects under the default fetch setting, but manual redirects and cross-origin constraints can behave differently. Test a mock Response.redirect separately. In this case the returned keys [‘status’, ‘location’, ‘redirected’] are the evidence to inspect, not a claim that a real website is available. Compare the desired answer with an alternative that looks similar but measures something else..

Check the boundary. First substitute topic “Art & Coding” for ‘Science & Art’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this interpret redirects before reading data case in a recycled-materials tally, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The next step should be one small controlled variation, not ten simultaneous edits. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: interpret redirects before reading data — a home garden observation chart

A pupil builds a little a home garden observation chart and wants to understand interpret redirects before reading data. With topic ‘Math + sketches’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is the response url and redirected flag can reveal a followed redirect; a redirect is not necessarily a permission or security success.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=4;
const topic="Math + sketches";
const r=Response.redirect('https://practice.invalid/new-path',302);const result={status:r.status,location:r.headers.get('location'),redirected:r.redirected};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For interpret redirects before reading data in a home garden observation chart, with the hypothetical ‘Math + sketches’ topic and count 4, the independently executed Node.js Web API test prints {“status”:302,”location”:”https://practice.invalid/new-path”,”redirected”:false}. Its observable properties are specific: An explicitly constructed redirect Response represents status 302 with a Location header. Its redirected property is not true, because the local object did not result from an actually followed redirect chain. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For interpret redirects before reading data in a home garden observation chart, start with the code expression responsible for the result: Manual redirect handling in a browser may conceal cross-origin Location and return an opaque redirect, depending on fetch mode and constraints. The controlled topic is ‘Math + sketches’ and the mock count is 4. Browsers usually follow redirects under the default fetch setting, but manual redirects and cross-origin constraints can behave differently. Test a mock Response.redirect separately. In this case the returned keys [‘status’, ‘location’, ‘redirected’] are the evidence to inspect, not a claim that a real website is available. Cross-check with an independent hand calculation using the smallest workable values..

Check the boundary. Now replace the invented count 4 with 9, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this interpret redirects before reading data case in a home garden observation chart, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A clear explanation is more valuable than guessing an answer from the display. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: interpret redirects before reading data — a public-transport timing experiment

The make-believe records for a public-transport timing experiment contain 16 observations under topic ‘Math + sketches’. A friend says the program has worked because the console displays something. Test interpret redirects before reading data: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is the response url and redirected flag can reveal a followed redirect; a redirect is not necessarily a permission or security success.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=16;
const topic="Math + sketches";
const r=Response.redirect('https://practice.invalid/new-path',307);const result={status:r.status,location:r.headers.get('location'),redirected:r.redirected};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For interpret redirects before reading data in a public-transport timing experiment, with the hypothetical ‘Math + sketches’ topic and count 16, the independently executed Node.js Web API test prints {“status”:307,”location”:”https://practice.invalid/new-path”,”redirected”:false}. Its observable properties are specific: An explicitly constructed redirect Response represents status 307 with a Location header. Its redirected property is not true, because the local object did not result from an actually followed redirect chain. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For interpret redirects before reading data in a public-transport timing experiment, start with the code expression responsible for the result: Manual redirect handling in a browser may conceal cross-origin Location and return an opaque redirect, depending on fetch mode and constraints. The controlled topic is ‘Math + sketches’ and the mock count is 16. Browsers usually follow redirects under the default fetch setting, but manual redirects and cross-origin constraints can behave differently. Test a mock Response.redirect separately. In this case the returned keys [‘status’, ‘location’, ‘redirected’] are the evidence to inspect, not a claim that a real website is available. Carry the result back to the family’s original decision, without claiming more than the data support..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a public-transport timing experiment, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this interpret redirects before reading data case in a public-transport timing experiment, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. No real pupil information is needed; the test data are deliberately imaginary. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: interpret redirects before reading data — a fictional club membership register

After a shared family activity around a fictional club membership register, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Coastal habitats?’ and the invented integer 8. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is the response url and redirected flag can reveal a followed redirect; a redirect is not necessarily a permission or security success.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=8;
const topic="Coastal habitats?";
const r=Response.redirect('https://practice.invalid/new-path',308);const result={status:r.status,location:r.headers.get('location'),redirected:r.redirected};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For interpret redirects before reading data in a fictional club membership register, with the hypothetical ‘Coastal habitats?’ topic and count 8, the independently executed Node.js Web API test prints {“status”:308,”location”:”https://practice.invalid/new-path”,”redirected”:false}. Its observable properties are specific: An explicitly constructed redirect Response represents status 308 with a Location header. Its redirected property is not true, because the local object did not result from an actually followed redirect chain. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For interpret redirects before reading data in a fictional club membership register, start with the code expression responsible for the result: Manual redirect handling in a browser may conceal cross-origin Location and return an opaque redirect, depending on fetch mode and constraints. The controlled topic is ‘Coastal habitats?’ and the mock count is 8. Browsers usually follow redirects under the default fetch setting, but manual redirects and cross-origin constraints can behave differently. Test a mock Response.redirect separately. In this case the returned keys [‘status’, ‘location’, ‘redirected’] are the evidence to inspect, not a claim that a real website is available. Explain the result in ordinary language before trusting a convenient display..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “concluding a redirect happened simply because a url string contains a path change.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this interpret redirects before reading data case in a fictional club membership register, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. When the result surprises the learner, keep the counterexample in the practice notes. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe interpret redirects before reading data in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Compare a synthetic 302 response with a final 200 response without calling any remote server. A useful parent prompt is to request a prediction, not a memorised command.

CHAPTER 18 OF 20 · Back to contents

18. Understand cache options without inventing performance results

Start with the answer: A Request cache option expresses a cache policy; it does not guarantee a particular browser cache hit or speedup.

Caching is governed by the browser environment, HTTP headers, cache partitioning and service workers. An offline mock can inspect options, not measure live cache behaviour.

Common tempting error: Claiming that cache: no-store makes a remote response instantaneous or immune to stale states.

Diagnostic for a parent or project partner: What does the request ask for, and what must be tested in a real browser?

Lab 1: understand cache options without inventing performance results — a home garden observation chart

For a fictional family a home garden observation chart, the response is delayed but arrives intact. The topic is ‘Punggol eco-notes’ and the controlled fixture uses count 2. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a request cache option expresses a cache policy; it does not guarantee a particular browser cache hit or speedup.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=2;
const topic="Punggol eco-notes";
const r=new Request('https://practice.invalid/resources',{cache:'default'});const result={cache:r.cache,method:r.method};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For understand cache options without inventing performance results in a home garden observation chart, with the hypothetical ‘Punggol eco-notes’ topic and count 2, the independently executed Node.js Web API test prints {“cache”:”default”,”method”:”GET”}. Its observable properties are specific: The local Request object records cache mode default, but this test cannot tell whether any real browser cache would be hit. The chosen property expresses intent, not measured performance. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For understand cache options without inventing performance results in a home garden observation chart, start with the code expression responsible for the result: A real evaluation uses a controlled server, browser developer tools and known HTTP cache headers rather than invented speed measurements. The controlled topic is ‘Punggol eco-notes’ and the mock count is 2. Caching is governed by the browser environment, HTTP headers, cache partitioning and service workers. An offline mock can inspect options, not measure live cache behaviour. In this case the returned keys [‘cache’, ‘method’] are the evidence to inspect, not a claim that a real website is available. Keep the input unchanged while adjusting a single condition..

Check the boundary. First substitute topic “Art & Coding” for ‘Punggol eco-notes’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this understand cache options without inventing performance results case in a home garden observation chart, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Save the example so the learner can rerun it with a fresh number next week. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: understand cache options without inventing performance results — a mock fundraising spreadsheet

A pupil builds a little a mock fundraising spreadsheet and wants to understand understand cache options without inventing performance results. With topic ‘Science & Art’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a request cache option expresses a cache policy; it does not guarantee a particular browser cache hit or speedup.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=11;
const topic="Science & Art";
const r=new Request('https://practice.invalid/resources',{cache:'no-store'});const result={cache:r.cache,method:r.method};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For understand cache options without inventing performance results in a mock fundraising spreadsheet, with the hypothetical ‘Science & Art’ topic and count 11, the independently executed Node.js Web API test prints {“cache”:”no-store”,”method”:”GET”}. Its observable properties are specific: The local Request object records cache mode no-store, but this test cannot tell whether any real browser cache would be hit. The chosen property expresses intent, not measured performance. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For understand cache options without inventing performance results in a mock fundraising spreadsheet, start with the code expression responsible for the result: A real evaluation uses a controlled server, browser developer tools and known HTTP cache headers rather than invented speed measurements. The controlled topic is ‘Science & Art’ and the mock count is 11. Caching is governed by the browser environment, HTTP headers, cache partitioning and service workers. An offline mock can inspect options, not measure live cache behaviour. In this case the returned keys [‘cache’, ‘method’] are the evidence to inspect, not a claim that a real website is available. Predict the behaviour before running a test; the difference between prediction and result is the learning target..

Check the boundary. Now replace the invented count 11 with 16, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this understand cache options without inventing performance results case in a mock fundraising spreadsheet, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. This is a proposed home exercise rather than a service or school claim. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: understand cache options without inventing performance results — a fictional club membership register

The make-believe records for a fictional club membership register contain 6 observations under topic ‘Science & Art’. A friend says the program has worked because the console displays something. Test understand cache options without inventing performance results: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a request cache option expresses a cache policy; it does not guarantee a particular browser cache hit or speedup.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=6;
const topic="Science & Art";
const r=new Request('https://practice.invalid/resources',{cache:'reload'});const result={cache:r.cache,method:r.method};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For understand cache options without inventing performance results in a fictional club membership register, with the hypothetical ‘Science & Art’ topic and count 6, the independently executed Node.js Web API test prints {“cache”:”reload”,”method”:”GET”}. Its observable properties are specific: The local Request object records cache mode reload, but this test cannot tell whether any real browser cache would be hit. The chosen property expresses intent, not measured performance. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For understand cache options without inventing performance results in a fictional club membership register, start with the code expression responsible for the result: A real evaluation uses a controlled server, browser developer tools and known HTTP cache headers rather than invented speed measurements. The controlled topic is ‘Science & Art’ and the mock count is 6. Caching is governed by the browser environment, HTTP headers, cache partitioning and service workers. An offline mock can inspect options, not measure live cache behaviour. In this case the returned keys [‘cache’, ‘method’] are the evidence to inspect, not a claim that a real website is available. Start by identifying the unit of observation, then apply only the rule relevant to that unit..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a fictional club membership register, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this understand cache options without inventing performance results case in a fictional club membership register, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The goal is not to finish a huge worksheet; it is to explain one reliable decision. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: understand cache options without inventing performance results — a fictional class activity log

After a shared family activity around a fictional class activity log, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Math + sketches’ and the invented integer 15. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is a request cache option expresses a cache policy; it does not guarantee a particular browser cache hit or speedup.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=15;
const topic="Math + sketches";
const r=new Request('https://practice.invalid/resources',{cache:'force-cache'});const result={cache:r.cache,method:r.method};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For understand cache options without inventing performance results in a fictional class activity log, with the hypothetical ‘Math + sketches’ topic and count 15, the independently executed Node.js Web API test prints {“cache”:”force-cache”,”method”:”GET”}. Its observable properties are specific: The local Request object records cache mode force-cache, but this test cannot tell whether any real browser cache would be hit. The chosen property expresses intent, not measured performance. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For understand cache options without inventing performance results in a fictional class activity log, start with the code expression responsible for the result: A real evaluation uses a controlled server, browser developer tools and known HTTP cache headers rather than invented speed measurements. The controlled topic is ‘Math + sketches’ and the mock count is 15. Caching is governed by the browser environment, HTTP headers, cache partitioning and service workers. An offline mock can inspect options, not measure live cache behaviour. In this case the returned keys [‘cache’, ‘method’] are the evidence to inspect, not a claim that a real website is available. Check the case that would make a tempting shortcut wrong..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “claiming that cache: no-store makes a remote response instantaneous or immune to stale states.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this understand cache options without inventing performance results case in a fictional class activity log, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The next step should be one small controlled variation, not ten simultaneous edits. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe understand cache options without inventing performance results in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Inspect two toy Request objects and reserve network-performance claims for instrumented measurements. The goal is not to finish a huge worksheet; it is to explain one reliable decision.

CHAPTER 19 OF 20 · Back to contents

19. Treat CORS and opaque responses as browser-enforced boundaries

Start with the answer: Setting mode: no-cors does not grant script access to another origin’s private response body.

Cross-origin permission depends on request mode, server policy, browser restrictions and other conditions. A URL comparison is only an origin exercise, not a real CORS enforcement test.

Common tempting error: Using no-cors to bypass a denied request and expecting JSON to become readable.

Diagnostic for a parent or project partner: Does the destination authorise this origin to read a response?

Lab 1: treat cors and opaque responses as browser-enforced boundaries — a mock fundraising spreadsheet

For a fictional family a mock fundraising spreadsheet, the response is delayed but arrives intact. The topic is ‘Coastal habitats?’ and the controlled fixture uses count 9. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is setting mode: no-cors does not grant script access to another origin’s private response body.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=9;
const topic="Coastal habitats?";
const home=new URL('https://practice.invalid/');const dest=new URL("https://practice.invalid/activities");const result={originA:home.origin,originB:dest.origin,sameOrigin:home.origin===dest.origin};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For treat cors and opaque responses as browser-enforced boundaries in a mock fundraising spreadsheet, with the hypothetical ‘Coastal habitats?’ topic and count 9, the independently executed Node.js Web API test prints {“originA”:”https://practice.invalid”,”originB”:”https://practice.invalid”,”sameOrigin”:true}. Its observable properties are specific: A string-level URL origin comparison checks scheme, host and port. It cannot emulate browser CORS enforcement, forbidden headers, credentials or server Access-Control-Allow-Origin decisions. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For treat cors and opaque responses as browser-enforced boundaries in a mock fundraising spreadsheet, start with the code expression responsible for the result: No special fetch mode here bypasses policy. In a real browser, no-cors typically leaves the script with an opaque unreadable cross-origin response. The controlled topic is ‘Coastal habitats?’ and the mock count is 9. Cross-origin permission depends on request mode, server policy, browser restrictions and other conditions. A URL comparison is only an origin exercise, not a real CORS enforcement test. In this case the returned keys [‘originA’, ‘originB’, ‘sameOrigin’] are the evidence to inspect, not a claim that a real website is available. Name which records enter the calculation and which stay outside..

Check the boundary. First substitute topic “Art & Coding” for ‘Coastal habitats?’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this treat cors and opaque responses as browser-enforced boundaries case in a mock fundraising spreadsheet, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Try this on a small, invented table before using any real schoolwork. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: treat cors and opaque responses as browser-enforced boundaries — a toy digital noticeboard

A pupil builds a little a toy digital noticeboard and wants to understand treat cors and opaque responses as browser-enforced boundaries. With topic ‘Punggol eco-notes’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is setting mode: no-cors does not grant script access to another origin’s private response body.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=18;
const topic="Punggol eco-notes";
const home=new URL('https://practice.invalid/');const dest=new URL("https://data.invalid/activities");const result={originA:home.origin,originB:dest.origin,sameOrigin:home.origin===dest.origin};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For treat cors and opaque responses as browser-enforced boundaries in a toy digital noticeboard, with the hypothetical ‘Punggol eco-notes’ topic and count 18, the independently executed Node.js Web API test prints {“originA”:”https://practice.invalid”,”originB”:”https://data.invalid”,”sameOrigin”:false}. Its observable properties are specific: A string-level URL origin comparison checks scheme, host and port. It cannot emulate browser CORS enforcement, forbidden headers, credentials or server Access-Control-Allow-Origin decisions. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For treat cors and opaque responses as browser-enforced boundaries in a toy digital noticeboard, start with the code expression responsible for the result: No special fetch mode here bypasses policy. In a real browser, no-cors typically leaves the script with an opaque unreadable cross-origin response. The controlled topic is ‘Punggol eco-notes’ and the mock count is 18. Cross-origin permission depends on request mode, server policy, browser restrictions and other conditions. A URL comparison is only an origin exercise, not a real CORS enforcement test. In this case the returned keys [‘originA’, ‘originB’, ‘sameOrigin’] are the evidence to inspect, not a claim that a real website is available. Ask whether the structure remains valid when the number of records doubles..

Check the boundary. Now replace the invented count 18 with 23, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this treat cors and opaque responses as browser-enforced boundaries case in a toy digital noticeboard, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. No real pupil information is needed; the test data are deliberately imaginary. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: treat cors and opaque responses as browser-enforced boundaries — a fictional class activity log

The make-believe records for a fictional class activity log contain 13 observations under topic ‘Punggol eco-notes’. A friend says the program has worked because the console displays something. Test treat cors and opaque responses as browser-enforced boundaries: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is setting mode: no-cors does not grant script access to another origin’s private response body.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=13;
const topic="Punggol eco-notes";
const home=new URL('https://practice.invalid/');const dest=new URL("http://practice.invalid/activities");const result={originA:home.origin,originB:dest.origin,sameOrigin:home.origin===dest.origin};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For treat cors and opaque responses as browser-enforced boundaries in a fictional class activity log, with the hypothetical ‘Punggol eco-notes’ topic and count 13, the independently executed Node.js Web API test prints {“originA”:”https://practice.invalid”,”originB”:”http://practice.invalid”,”sameOrigin”:false}. Its observable properties are specific: A string-level URL origin comparison checks scheme, host and port. It cannot emulate browser CORS enforcement, forbidden headers, credentials or server Access-Control-Allow-Origin decisions. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For treat cors and opaque responses as browser-enforced boundaries in a fictional class activity log, start with the code expression responsible for the result: No special fetch mode here bypasses policy. In a real browser, no-cors typically leaves the script with an opaque unreadable cross-origin response. The controlled topic is ‘Punggol eco-notes’ and the mock count is 13. Cross-origin permission depends on request mode, server policy, browser restrictions and other conditions. A URL comparison is only an origin exercise, not a real CORS enforcement test. In this case the returned keys [‘originA’, ‘originB’, ‘sameOrigin’] are the evidence to inspect, not a claim that a real website is available. Draw a miniature table and count the rows before calculating any summary..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a fictional class activity log, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this treat cors and opaque responses as browser-enforced boundaries case in a fictional class activity log, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Independent checking beats a polished screen that nobody can explain. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: treat cors and opaque responses as browser-enforced boundaries — a coastal ecology observation workbook

After a shared family activity around a coastal ecology observation workbook, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Science & Art’ and the invented integer 5. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is setting mode: no-cors does not grant script access to another origin’s private response body.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=5;
const topic="Science & Art";
const home=new URL('https://practice.invalid/');const dest=new URL("https://practice.invalid:444/activities");const result={originA:home.origin,originB:dest.origin,sameOrigin:home.origin===dest.origin};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For treat cors and opaque responses as browser-enforced boundaries in a coastal ecology observation workbook, with the hypothetical ‘Science & Art’ topic and count 5, the independently executed Node.js Web API test prints {“originA”:”https://practice.invalid”,”originB”:”https://practice.invalid:444″,”sameOrigin”:false}. Its observable properties are specific: A string-level URL origin comparison checks scheme, host and port. It cannot emulate browser CORS enforcement, forbidden headers, credentials or server Access-Control-Allow-Origin decisions. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For treat cors and opaque responses as browser-enforced boundaries in a coastal ecology observation workbook, start with the code expression responsible for the result: No special fetch mode here bypasses policy. In a real browser, no-cors typically leaves the script with an opaque unreadable cross-origin response. The controlled topic is ‘Science & Art’ and the mock count is 5. Cross-origin permission depends on request mode, server policy, browser restrictions and other conditions. A URL comparison is only an origin exercise, not a real CORS enforcement test. In this case the returned keys [‘originA’, ‘originB’, ‘sameOrigin’] are the evidence to inspect, not a claim that a real website is available. Compare the desired answer with an alternative that looks similar but measures something else..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “using no-cors to bypass a denied request and expecting json to become readable.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this treat cors and opaque responses as browser-enforced boundaries case in a coastal ecology observation workbook, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Save the example so the learner can rerun it with a fresh number next week. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe treat cors and opaque responses as browser-enforced boundaries in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Compare origins safely and explain what a browser, not this local string check, enforces. When the result surprises the learner, keep the counterexample in the practice notes.

CHAPTER 20 OF 20 · Back to contents

20. Design UI states that preserve evidence

Start with the answer: Loading, successful-empty, HTTP error, parse error, network error and cancellation are different application states.

A parent can check the reasoning without writing the interface: change one condition at a time and require a cause-specific label. This is practical debugging and honest communication.

Common tempting error: Collapsing every non-ideal outcome into a spinner that never ends or a fabricated empty record.

Diagnostic for a parent or project partner: What evidence allows this exact state to be displayed?

Lab 1: design ui states that preserve evidence — a toy digital noticeboard

For a fictional family a toy digital noticeboard, the response is delayed but arrives intact. The topic is ‘Math + sketches’ and the controlled fixture uses count 16. Before running the snippet, decide whether the code tests protocol status, a body reader, URL construction or a state transition. Write the predicted result as a small object with named fields. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is loading, successful-empty, http error, parse error, network error and cancellation are different application states.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=16;
const topic="Math + sketches";
const r=new Response("[]",{status:200,headers:{'Content-Type':'application/json'}});let state;if(!r.ok)state='http-error';else if(r.status===204)state='success-no-body';else{try{const d=await r.json();state=Array.isArray(d)&&d.length===0?'empty':'success-data';}catch(e){state='format-error';}}const result={status:r.status,state};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For design ui states that preserve evidence in a toy digital noticeboard, with the hypothetical ‘Math + sketches’ topic and count 16, the independently executed Node.js Web API test prints {“status”:200,”state”:”empty”}. Its observable properties are specific: The local UI classifier distinguishes a status failure, a bodyless success, an empty-array success, populated data and a bad representation. This particular case exercises one branch. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For design ui states that preserve evidence in a toy digital noticeboard, start with the code expression responsible for the result: Real network rejection and user-initiated cancellation require additional branches, which should not be silently relabelled as empty data. The controlled topic is ‘Math + sketches’ and the mock count is 16. A parent can check the reasoning without writing the interface: change one condition at a time and require a cause-specific label. This is practical debugging and honest communication. In this case the returned keys [‘status’, ‘state’] are the evidence to inspect, not a claim that a real website is available. Cross-check with an independent hand calculation using the smallest workable values..

Check the boundary. First substitute topic “Art & Coding” for ‘Math + sketches’. Then ask whether the mechanism under test uses the topic as data, URL-encoded input, or merely a displayed explanation. A field that should remain unaffected must be identified before the next run; changing an unrelated label cannot repair a HTTP error. For this design ui states that preserve evidence case in a toy digital noticeboard, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. A Punggol family can practise this with fictional numbers after dinner or over a weekend. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 2: design ui states that preserve evidence — a family revision tracker

A pupil builds a little a family revision tracker and wants to understand design ui states that preserve evidence. With topic ‘Coastal habitats?’, ask which evidence is available from a local Request or Response constructor. Predict the output, state what the code never contacts, and identify an ordinary browser condition that could behave differently. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is loading, successful-empty, http error, parse error, network error and cancellation are different application states.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=8;
const topic="Coastal habitats?";
const r=new Response("{\"items\":[1]}",{status:404,headers:{'Content-Type':'application/json'}});let state;if(!r.ok)state='http-error';else if(r.status===204)state='success-no-body';else{try{const d=await r.json();state=Array.isArray(d)&&d.length===0?'empty':'success-data';}catch(e){state='format-error';}}const result={status:r.status,state};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For design ui states that preserve evidence in a family revision tracker, with the hypothetical ‘Coastal habitats?’ topic and count 8, the independently executed Node.js Web API test prints {“status”:404,”state”:”http-error”}. Its observable properties are specific: The local UI classifier distinguishes a status failure, a bodyless success, an empty-array success, populated data and a bad representation. This particular case exercises one branch. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For design ui states that preserve evidence in a family revision tracker, start with the code expression responsible for the result: Real network rejection and user-initiated cancellation require additional branches, which should not be silently relabelled as empty data. The controlled topic is ‘Coastal habitats?’ and the mock count is 8. A parent can check the reasoning without writing the interface: change one condition at a time and require a cause-specific label. This is practical debugging and honest communication. In this case the returned keys [‘status’, ‘state’] are the evidence to inspect, not a claim that a real website is available. Write down the unsuccessful interpretation and explain why it fails..

Check the boundary. Now replace the invented count 8 with 13, leaving the response status and method unchanged unless the exercise explicitly uses count in its payload. If the result changes, say exactly which expression consumes count. If it does not, explain why an unused local number cannot alter a network or browser property. For this design ui states that preserve evidence case in a family revision tracker, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. The goal is not to finish a huge worksheet; it is to explain one reliable decision. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 3: design ui states that preserve evidence — a coastal ecology observation workbook

The make-believe records for a coastal ecology observation workbook contain 3 observations under topic ‘Coastal habitats?’. A friend says the program has worked because the console displays something. Test design ui states that preserve evidence: describe the rule, the exact output, and at least one plausible but false interpretation. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is loading, successful-empty, http error, parse error, network error and cancellation are different application states.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=3;
const topic="Coastal habitats?";
const r=new Response("{broken",{status:200,headers:{'Content-Type':'application/json'}});let state;if(!r.ok)state='http-error';else if(r.status===204)state='success-no-body';else{try{const d=await r.json();state=Array.isArray(d)&&d.length===0?'empty':'success-data';}catch(e){state='format-error';}}const result={status:r.status,state};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For design ui states that preserve evidence in a coastal ecology observation workbook, with the hypothetical ‘Coastal habitats?’ topic and count 3, the independently executed Node.js Web API test prints {“status”:200,”state”:”format-error”}. Its observable properties are specific: The local UI classifier distinguishes a status failure, a bodyless success, an empty-array success, populated data and a bad representation. This particular case exercises one branch. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For design ui states that preserve evidence in a coastal ecology observation workbook, start with the code expression responsible for the result: Real network rejection and user-initiated cancellation require additional branches, which should not be silently relabelled as empty data. The controlled topic is ‘Coastal habitats?’ and the mock count is 3. A parent can check the reasoning without writing the interface: change one condition at a time and require a cause-specific label. This is practical debugging and honest communication. In this case the returned keys [‘status’, ‘state’] are the evidence to inspect, not a claim that a real website is available. Explain the result in ordinary language before trusting a convenient display..

Check the boundary. Ask the learner to draw the asynchronous stages: create a Request or Response; obtain or reject the response; check status; consume an appropriate body; validate data; change UI state. For a coastal ecology observation workbook, mark the one stage exercised here and a stage that cannot be established without a real authorised endpoint. For this design ui states that preserve evidence case in a coastal ecology observation workbook, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Treat a version-dependent result as a prompt to consult the current official manual. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Lab 4: design ui states that preserve evidence — an after-CCA practice planner

After a shared family activity around an after-CCA practice planner, a learner wants to debug a simple fetch flow. Their test uses the literal label ‘Punggol eco-notes’ and the invented integer 12. Ask for a prediction on paper, run the local Node snippet, and then explain whether the result proves any genuine server or school claim. This is intentionally isolated; do not execute unapproved writes on a real endpoint. The target of the exercise is loading, successful-empty, http error, parse error, network error and cancellation are different application states.

// Runnable locally in a modern Node.js with global Request/Response.
// No real network request is made.
(async()=>{
const count=12;
const topic="Punggol eco-notes";
const r=new Response(null,{status:204,headers:{'Content-Type':'application/json'}});let state;if(!r.ok)state='http-error';else if(r.status===204)state='success-no-body';else{try{const d=await r.json();state=Array.isArray(d)&&d.length===0?'empty':'success-data';}catch(e){state='format-error';}}const result={status:r.status,state};
console.log(JSON.stringify(result));
})().catch(e=>{console.error(e.stack);process.exit(3);});

Worked answer. For design ui states that preserve evidence in an after-CCA practice planner, with the hypothetical ‘Punggol eco-notes’ topic and count 12, the independently executed Node.js Web API test prints {“status”:204,”state”:”success-no-body”}. Its observable properties are specific: The local UI classifier distinguishes a status failure, a bodyless success, an empty-array success, populated data and a bad representation. This particular case exercises one branch. This experiment does not contact a school service or rely on live remote-network outcomes, so the output is repeatable for a learner or parent who uses a compatible modern runtime.

What makes that answer true. For design ui states that preserve evidence in an after-CCA practice planner, start with the code expression responsible for the result: Real network rejection and user-initiated cancellation require additional branches, which should not be silently relabelled as empty data. The controlled topic is ‘Punggol eco-notes’ and the mock count is 12. A parent can check the reasoning without writing the interface: change one condition at a time and require a cause-specific label. This is practical debugging and honest communication. In this case the returned keys [‘status’, ‘state’] are the evidence to inspect, not a claim that a real website is available. Keep the input unchanged while adjusting a single condition..

Check the boundary. Rerun the current script as a safe home demonstration, then write a counterexample that would make the tempting error “collapsing every non-ideal outcome into a spinner that never ends or a fabricated empty record.” visible. The diagnosis should name the rejected promise, HTTP status, decode failure, permissions rule or UI-state transition involved, not merely say “it failed”. For this design ui states that preserve evidence case in an after-CCA practice planner, an acceptable counterexample must directly test that specific rule rather than an unrelated JavaScript feature. Try this on a small, invented table before using any real schoolwork. The right learning evidence is a prediction, an observed output and one causal explanation recorded together.

Explain it without the screen

At the end of this chapter, remove the working code from view. Ask the learner to describe design ui states that preserve evidence in a new example, identify the input that matters, and state which visible evidence could falsify the first answer. A parent can listen for the causal step rather than attempting to memorise library or application syntax. The best checkpoint is a tiny counterexample saved alongside the successful case.

Chapter decision: Test a local classifier with distinct status and data outcomes. Independent checking beats a polished screen that nobody can explain.

Parent decision route: what should happen next?

Step 1. First ask for the status and the exact operation that failed: obtaining a Response, validating its HTTP status, decoding the body, or updating a screen. A learner who can point to the failing stage already has a reproducible diagnosis.

Step 2. If the difficulty is reading the code, draw a three-box timeline: request, response headers/status, and body reader. Try only statuses 200 and 404 until those two branches are clear.

Step 3. If the learner understands basic response status but makes mistakes with promises, practise a deliberately malformed JSON response, a 204 bodyless response and a rejected mock transport in an isolated environment.

Step 4. If the learner is building a small family study tracker, test an empty successful result separately from a server 404. Empty data are an answer; an unavailable resource is a different condition.

Step 5. For cross-origin or authentication trouble, consult the real API contract and get authorised support from its owner. Never bypass access controls or copy session credentials into a forum or tutoring worksheet.

Step 6. Choose technical guidance by the exact mismatch: URL assembly, async sequencing, response status, JSON structure, CORS rules or UI state. A generic promise of faster coding is less helpful than correcting the cause.

Step 7. Retain one tiny runnable success case and one counterexample showing its boundary. In a Punggol family routine, a weekend ten-minute demonstration with invented activities can build better confidence than many unexamined copied snippets.

Frequently asked questions

Does fetch reject when the server returns 404?

No, an ordinary HTTP 404 fulfills fetch with a Response. Check response.ok or status and handle the error deliberately. Transport failures may reject the fetch promise.

What is the range for response.ok?

It is true for HTTP status codes 200–299 inclusive. It says nothing by itself about whether JSON is valid.

Can response.json() fail after response.ok is true?

Yes. The returned body may be invalid JSON or there may be a body-reading error. Catch and report that stage separately.

Why did my code fail when I read text and then JSON?

The Response body is a stream. After successful consumption you cannot normally consume that same original body again.

What should I do with 204 No Content?

Handle the documented successful operation without assuming a JSON body exists. Do not invent a returned object.

Will no-cors let a webpage read blocked cross-origin data?

No. An opaque browser response does not reveal the body to JavaScript. Follow the server policy and authorised CORS configuration.

Does a timeout mean the server made no change?

No. The request may have reached the server even if its response was not received. Do not blindly retry writes.

Is it safe to expose a key in sample frontend code?

No. Do not place real keys or student data in public sample code. Use entirely fake credentials in mock exercises.

Do all APIs use JSON?

No. Some use text, forms, binary media or return no body. Consult the documented representation before selecting a reader.

Do these topics appear in every Singapore MOE or SEAB exam syllabus?

No syllabus coverage is asserted here. These are programming and digital literacy enrichment exercises. Check official subject syllabuses for the relevant course and cohort.

How can a parent test understanding without coding?

Ask the child to name the evidence available at each step, predict what changes between 200 and 404, and explain a single counterexample before running code.

What practice should a learner save after completing this guide?

Keep a short reproducible local script, its observed output, one changed assumption and a written reason the result changed. That record can guide subsequent independent work.

Primary sources and scope

Primary documentation: MDN Web Docs: Using the Fetch API. Read the current version notes or compatibility statements before using a different software version from these examples.

Further verified reference: WHATWG Fetch living standard.

Further verified reference: MDN Response interface.

Further verified reference: MDN AbortController.

This educational casebook was reviewed 17 October 2026. Invented datasets and classroom scenarios are shown explicitly as examples, not reports about actual Punggol students. Singapore curriculum details are not attributed to a syllabus without current official MOE or SEAB source checks. These techniques are coding, digital literacy and problem-solving enrichment, not claims that a particular programming API is assessed at a particular level.

Continue from here: Start Here · Tuition · Education · Pathways · Parenting 101 · All Site Routes

eduKate Punggol

Contact

83 Punggol Central, Singapore 828761

edu|Kate Bukit Timah

8 Fourth Avenue, Singapore 268674

By Appointment +65 8823 1234
admin@edukatesg.com

Email Us

When a child finally understands, school becomes less frightening and the future opens wider. Email us for the latest schedules and fees.

← 返回

感谢您的回复。 ✨

了解 eduKate Punggol 的更多信息

立即订阅以继续阅读并访问完整档案。

继续阅读