← Fundamentals
Fundamentals

Side effects and pure functions

What changes besides the return value, and when does calling a function again change the answer?

A function’s returned answer and its effects on surrounding state are separate parts of its behavior.

Outcome

Say what a function reads and changes besides its arguments and result, keep calculations pure where you can, make each effect happen exactly when intended, and store the result of a call with an effect instead of repeating it.

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.

Side effect
Anything a function does besides computing its result: changing outside state or arguments, printing, reading input.
Pure function
A function whose result depends only on its arguments and which has no side effects.
Hidden input
Outside state a function reads that is not one of its arguments.
Short-circuit evaluation
&& and || skip their right side when the left side already decides the result.

Results, inputs and outward effects

A pure function computes its result from its arguments without side effects. Reading changing outside state introduces a hidden input; changing caller-visible data or performing I/O adds an effect. Local calculation state can change while the function remains pure, provided those changes do not escape.

To assess a call, inspect both its body and the path that reaches it. A signature can permit particular access without describing every effect, and conditional evaluation can skip a call entirely. Reusing a calculated answer and repeating an outward action require different decisions.

01Hidden inputs

A function that reads outside state can give different answers for the same call

A café till is being checked before its order preview is reused in checkout. Quotes should depend on the current customer, and previewing a total should leave the cart ready for checkout. The same tool also records every submitted line and posts account changes. The engineer needs to separate a calculated answer from the state changed while obtaining it.

A quote preview must remain understandable when the till’s active discount changes. This reduced probe calls price(100), changes a discount outside the function and calls price(100) again. Predict both lines, then identify the input missing from the call.

discount is a package-level var.

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

import "fmt"

var discount = 10

func price(amount int) int {
	return amount - discount
}

func main() {
	fmt.Println(price(100))
	discount = 20

	fmt.Println(price(100))
}
What do the two calls 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.

02Changed arguments

Changes to the cart persist into its next preview

The till can preview a cart repeatedly before checkout. totalWithTax adds 10% and sums two prices of 50, then the caller requests the same preview again on that cart. Predict both lines and account for what the second call receives.

totalWithTax writes prices[i] *= 1.1 on its slice.

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

import (
	"fmt"
	"math"
)

func totalWithTax(prices []float64) float64 {
	total := 0.0

	for i := range prices {
		prices[i] *= 1.1
		total += prices[i]
	}

	return math.Round(total)
}

func main() {
	cart := []float64{50, 50}

	fmt.Println(totalWithTax(cart))
	fmt.Println(totalWithTax(cart))
}
What do the two calls print?

03Effects in conditions

An effect on the right of && or || may never run

Before wiring checkout, the engineer reduces a conditional posting path to a charge counter. charge increments the counter and returns true. With items set to 0, predict the final count and any message from the condition.

charge changes a package-level counter.

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

import "fmt"

var charges = 0

func charge() bool {
	charges++

	return true
}

func main() {
	items := 0

	if items > 0 && charge() {
		fmt.Println("charged")
	}

	fmt.Println("charges", charges)
}
What does the program print?

04Repair the café till

Quote from the arguments, audit every line, change the balance once

One café-till tool continues through three repairs. First make each quote depend only on the customer kind and amount it is given. Then make sure every order line is audited, whether or not it is accepted. Finally change the account balance once per line while still printing it and reporting an overdraft.

The lab opens in your reading language and has its own language control. Each file contains its imports, the reader, any supplied helpers and a complete main.

Repair the café till

Keep quotes independent of customer history, preserve auditing alongside acceptance, then post each balance change once.

  1. easy · F-EFFECT-V4-1 Quote from the arguments alone
  2. medium · F-EFFECT-V4-2 Audit every line
  3. hard · F-EFFECT-V4-3 Change the balance once
In the frontend Derive a quote while rendering; commit it from an explicit event. Optional

A till preview can rerender while the operator changes the amount. Derive the displayed quote from the supplied amount and discount without posting an order. A button handler is the explicit boundary that invokes commit. This separates rendering frequency from intentional checkout actions.

These client-side excerpts receive commit from a client parent. They show the UI boundary only; service retries, idempotency and server/client transport are outside this example.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

type Props = { amount: number; discount: number; commit: (price: number) => void };

export function QuotePreview({ amount, discount, commit }: Props) {
  const quoted = amount - discount;

  return (
    <>
      <p>Quote {quoted}</p>
      <button onClick={() => commit(quoted)}>Commit order</button>
    </>
  );
}

React can render again; the calculation stays free of outward writes. commit is invoked by the click handler rather than by rendering the component.

Sources: React: Keeping components pure,Svelte: $derived.

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.