← Fundamentals
Fundamentals

Closures and captured variables

How can a function use a name after the call that made it has returned, and does it see later changes?

A saved function carries an environment whose capture rules determine the state it can use later.

Outcome

Say what a closure keeps, predict whether it sees a later change, give each closure its own state where needed, and choose capture by value or by reference deliberately.

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.
Per-iteration loop variable
Under module language version 1.22 or later, variables declared by a for clause or range clause are separate per iteration; pre-existing assigned variables remain shared.

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 declared inside makeTracker; the returned func literal changes it.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

func makeTracker(name string) func() string {
	count := 0

	return func() string {
		count++

		return fmt.Sprint(name, " ", count)
	}
}

func main() {
	ana := makeTracker("ana")
	ben := makeTracker("ben")

	ana()

	fmt.Println(ana())
	fmt.Println(ben())
}
What do the two lines print?
Go · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
go run .

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 a func literal that returns price.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

func main() {
	price := 10
	show := func() int { return price }

	price = 12

	fmt.Println(show())
}
What does the program print?

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 declares i with :=, under Go language version 1.22 or later.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

func main() {
	var actions []func() int

	for i := 0; i < 3; i++ {
		actions = append(actions, func() int { return i })
	}

	fmt.Println(actions[0](), actions[1](), actions[2]())
}
What does the program print?
Loading Three closures, one i or three…

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.

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.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"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.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.