Ruth’s import now works the way the last lesson set it up. checkRun() throws where it finds a bad run, and the loop in importRuns() catches the error, reports the run, and skips it. However, a throw isn’t the only way a function can say that something didn’t work out. Some functions hand back a special value instead, such as undefined.
In this lesson, you’ll decide which of the two a function should use, and you’ll add your own context to a low-level error without losing what it already says. Start with a question a club member asks Ruth: When did someone first run this season?
Choose Between a Value and a Throw
Not every function that comes up empty has failed. Sometimes “nothing found” is the answer. This lesson works in Ruth’s season-log folder and needs only two of its files. If you don’t have them anymore, re-create them:
This package.json tells Node.js to treat the .js files as ES modules:
package.json
{ "type": "module" }
The season’s runs are in runs.json, covering the first three Saturdays:
runs.json
[
{ "id": 1, "runner": "Ruth Abebe", "date": "2026-04-04",
"distance": 5, "minutes": 27 },
{ "id": 2, "runner": "Priya Nair", "date": "2026-04-04",
"distance": 5, "minutes": 31 },
{ "id": 3, "runner": "Tomás Herrera", "date": "2026-04-04",
"distance": 8, "minutes": 44 },
{ "id": 4, "runner": "Grace Kim", "date": "2026-04-11",
"distance": 10, "minutes": 52 },
{ "id": 5, "runner": "Kwame Mensah", "date": "2026-04-11",
"distance": 5, "minutes": 24 },
{ "id": 6, "runner": "Ruth Abebe", "date": "2026-04-18",
"distance": 8, "minutes": 45 }
]
The project’s other files stay as they are, and this lesson doesn’t run them.
Two club members have questions for Ruth. Tomás wants to know when he first ran this season. Amara Okafor joined the club in May and asks whether she’s in the log yet. Ruth writes a new module, find.js, with a function that returns the first run under a runner’s name or undefined when there’s none:
find.js
export function findRunner(runs, name) {
for (const run of runs) {
if (run.runner === name) {
return run;
}
}
return undefined;
}
She asks both questions in a scratch file, try-find.js, which reads the season with readFileSync() and JSON.parse() and lets an if pick the line to print:
try-find.js
import { readFileSync } from "node:fs";
import { findRunner } from "./find.js";
const runs = JSON.parse(readFileSync("runs.json", "utf-8"));
for (const name of ["Tomás Herrera", "Amara Okafor"]) {
const run = findRunner(runs, name);
if (run === undefined) {
console.log(`${name}: no runs yet`);
} else {
console.log(`${name}: first ran on ${run.date}`);
}
}
The examples use Node.js 26. Run the scratch file, and both questions get an answer:
$ node try-find.js
Tomás Herrera: first ran on 2026-04-04
Amara Okafor: no runs yet