← Fundamentals
Fundamentals

Absence, zero, and empty values

Are no value, zero, false and an empty collection interchangeable?

Preserve the difference between a supplied value and no value.

Outcome

Keep absence apart from zero, false and empty values through lookups, defaults, parsing and aggregates, using each language’s presence information: undefined and ??, comma-ok and zero values, Option, and std::optional with find.

Terminology (6)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.

Absence
The state of having no value at all, as opposed to having a value such as 0, false or "".
Presence information
A separate fact saying whether a value exists: a found flag, an Option, an optional, or a missing key.
Default
A value supplied when the real one is absent.
Sentinel
An ordinary value, such as 0 or −1, used to mean “missing”; it fails when that value is also legitimate.
Empty collection
A collection that exists and holds no elements; it is a value, not an absence.
Nullish coalescing (??)
Supplies a default only for null or undefined, keeping 0, false and "".

Values and presence are separate facts

Zero, false and empty text can all be deliberate values. Absence says that no value was supplied. A representation may retain both facts through an optional value, a presence flag or a separate lookup; replacing absence with an ordinary value discards information.

Carry that distinction through lookup, conversion, defaults and aggregation. For example, an empty collection of measurements and a collection containing a measured zero describe different evidence. Choose a default only when the contract says those states should be treated alike.

01Missing keys

A missing key and a stored zero can look the same

A five-person coffee-break survey needs a coverage report as well as a cups-per-day average. Someone can answer 0, leave the answer blank or never enter the survey. The kiosk must preserve those states through its settings, submitted fields and final summary; treating them all as 0 invents answers and hides who still needs asking.

Before storing optional survey answers, test the register with a reduced numeric scores map. alice is recorded with 0 and bob was never added. The coverage report must preserve that distinction and its participant count. Predict both reads and the map size.

Map.get returns the stored value, or undefined. size counts entries.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const scores = new Map<string, number>([["alice", 0]]);

console.log(scores.get("alice"), scores.get("bob"), scores.size);
What does the program print?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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’s cmp.Or needs Go 1.22 or later; C++ contains needs C++20.

02Defaults

A default can replace a real zero

The survey kiosk has a saved volume of 0 because the pilot runs in a quiet room; bass was never configured. Its settings loader tries a default of 10 in two ways. Predict whether each approach preserves the saved setting while filling the omission.

|| returns its right side when the left side is falsy; ?? only when it is null or undefined.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const settings = new Map<string, number>([["volume", 0]]);

const volume = settings.get("volume");
const bass = settings.get("bass");

console.log(volume || 10, bass || 10);
console.log(volume ?? 10, bass ?? 10);
What do the two lines print?

03Blank input

Blank input is not the number zero

The pilot now receives form fields: "7", "0" and an empty string for a skipped question. Before adding them to the response register, inspect what each native conversion retains. Predict the empty field’s result.

Number(text) converts a string to a number.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
for (const field of ["7", "0", ""]) {
  console.log(JSON.stringify(field), Number(field));
}
What does the empty field become?

04Empty collections

An empty list is a value, but it has no average

The summary can reach a question with no given numeric answers, or one whose only answer is 0. This reduced average tests those two cases before the optional-answer aggregate. Predict what each program prints.

average divides a sum by values.length.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
function average(values: number[]): number {
  return values.reduce((sum, value) => sum + value, 0) / values.length;
}

console.log(average([]), average([0]));
What does the program print?

05Repair the survey

Read, report, then average the answers

Read optional responses, report survey coverage and summarize the given counts. The coverage report distinguishes a missing participant record from a recorded blank, and reading it must not enroll anyone. The aggregate combines optional records, so preserving zero matters to both its numerator and its answer count.

The pilot has at most five participants. Given answers are whole counts from 0 through 20; each question has one through five comma-separated fields, including blanks. Names are single tokens, and the report command and numeric syntax are supplied as valid input. These bounds keep totals small; the readers do not validate the pilot contract.

The lab opens in your reading language and has its own language control. Each file contains its imports, types, reader and complete main. Later levels supply the earlier correct helpers.

Repair the coffee survey

A blank that must not become zero, two kinds of absence in a lookup, then an average over answers that may not exist.

  1. easy · F-ABSENCE-V4-1 Read an optional answer
  2. medium · F-ABSENCE-V4-2 Report who answered
  3. hard · F-ABSENCE-V4-3 Average the answers
In the frontend Render a classified survey result without testing its numeric payload for presence. Optional

The survey summary cell receives a classified result: not-surveyed, blank, or answered with a cups count. That contract carries both record presence and answer presence into the UI. The answered variant can contain 0; the renderer chooses its label from the state tag, then prints the count.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type SurveyResponse =
  { kind: "not-surveyed" } | { kind: "blank" } | { kind: "answered"; cups: number };

export function SurveyCell({ response }: { response: SurveyResponse }) {
  const label =
    response.kind === "answered"
      ? `${response.cups} cups/day`
      : response.kind === "blank"
        ? "Question skipped"
        : "Not surveyed";

  return <output>{label}</output>;
}

This read-only component receives the classified response as a prop. An answered 0 prints 0 cups/day; blank and not-surveyed keep different labels.

Sources: React: passing props to a component,Svelte: $props.

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.