Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Closure
- A function together with the variables it uses from the scope where it was written.
- Capture
- Making an outer variable available inside a closure, as the variable itself, a reference or a copy.
- Maker function
- A function that creates and returns a closure, often with fresh state per call.
- var versus let
- var declares one variable for the whole function; let declares one per block, and per iteration in a for loop.
What a saved function retains
A closure combines callable code with access to values from its surrounding scope. Its captured environment can hold evolving state or facts intended to stay fixed when the function is prepared. Capturing a value, a variable or a reference can produce different relationships to later changes.
Follow creation and invocation as separate moments. Several closures may reach the same state, or each may retain its own state from a maker call or iteration. The selected native capture and lifetime rules determine which relationships the saved functions can safely keep.
01State in a closure
Keep each visitor’s tracker after intake returns
A front-desk tool keeps a visit tracker for each person. It also saves quoted prices and builds reminder batches that run after intake. Each saved function must retain the right part of the desk’s state: an ongoing visit count or facts fixed at the moment a quote or reminder was prepared.
The front desk wants one ongoing visit count per person. makeTracker returns a function the desk can keep and call on that visitor’s later arrivals. This probe creates trackers for ana and ben, then calls ana twice and ben once. Predict the two printed lines.
count is a let inside makeTracker; the returned arrow function changes it.
function makeTracker(name: string): () => string {
let count = 0;
return () => {
count += 1;
return `${name} ${count}`;
};
}
const ana = makeTracker("ana");
const ben = makeTracker("ben");
ana();
console.log(ana());
console.log(ben());
npx tsc --noEmit --strict main.ts && node main.ts
Use the selected language’s setup from the first reading and replace the file for each experiment. Go examples assume a module language version of at least 1.22. Inputs use valid single-word names/items and small nonnegative whole amounts/counts within the shown types.
02Variable or copy
Choose the price a saved quote should report
A quoted price may be shown after the desk updates its current price. Isolate that timing decision with one scalar price: make a reporting closure while it is 10, assign 12, then call the closure. Predict its output.
show is an arrow function that returns price.
let price = 10;
const show = () => price;
price = 12;
console.log(show());
03Closures made in a loop
Prepare a batch of callbacks before running them
The desk prepares every reminder before it runs the batch. First isolate the loop-binding question: three callbacks return their loop counter when called after construction finishes. Predict the line.
The loop is for (var i = 0; i < 3; i++).
const actions: (() => number)[] = [];
for (var i = 0; i < 3; i++) {
actions.push(() => i);
}
console.log(actions.map((action) => action()).join(" "));
04Repair the front desk
Count each visitor, keep quoted prices, give reminders their own names
Finish the desk’s saved-function policies: independent visit trackers, quoted prices that survive later price updates, and reminder pairs that keep their scheduled position and name while intake continues. Each file supplies the complete reader and caller context.
The lab opens in your reading language and has its own language control. Each file contains its imports, the reader and a complete main.
Repair the front desk
Retained visit state, quoted-price history, then scheduled position/name pairs.
In the frontend A retained handler follows the framework’s state-binding lifetime. Optional
The desk’s quote preview can keep a callback after creating it. React gives each render a state binding; Svelte reads a reactive binding that an assignment updates. These static handlers contrast those sources before choosing a saved-price policy.
"use client";
import { useState } from "react";
export default function QuotePreview() {
const [price, setPrice] = useState(10);
function preview() {
const quoted = price;
const read = () => price;
setPrice(price + 1);
console.log(quoted, read());
}
return <button onClick={preview}>Preview next price</button>;
}
Within this handler, quoted and read() both use the price binding from the render that created preview. setPrice requests another render; it does not change that binding. Retaining this callback later would still retain that render’s scalar price. This is a React render-state rule, not a guarantee that every captured object is deeply frozen.
Sources: React: state as a snapshot,Svelte: $state and passing state into functions.
Sign in to keep your read marks on every device. Sign in
Was this helpful?