Before you begin
Why this matters
When a program runs with the wrong setting, the first question is: where did this value come from? If you can follow the order in which your code looks, you can answer that by reading it, and you can spot the lines that replace what someone typed without reporting an error.
What this helps you reason about
- Predict which place a setting comes from when several disagree.
- Spot code that treats an empty value as missing, or swaps a bad value for the default.
- Write an error that says which place held the bad value.
A program often needs one setting, such as a port number, that can come from several places. This lesson builds the part of the program that picks one value, checks it, and says where it came from.
Already know this? The short version
- Take the setting from the highest source that is present, here flag, then environment variable, then file, then the default.
- Present means supplied, even as ""; test with !== undefined or ??, never with || or if (value), which treat "" as missing.
- Check only the chosen text, with your own rule (here 1 to 5 ASCII digits, then 1 to 65535), because Number accepts "", " 80", "1e3", and "0x50".
- An invalid winner is an error that names its source and text; never fall back to a lower source or to the default.
- Read process.argv, process.env, and files in one place, at the start of the program, and pass their text to a function you can call with any combination.
Words in this lesson (7)
- setting
- One value a program needs before it can do its work, such as the port number it listens on.
- source
- A place a setting can come from: a command-line flag, an environment variable, a configuration file, or a default written in the program.
- precedence
- The fixed order that decides which source wins when several supply the same setting. In this lesson: flag, then environment variable, then file, then default.
- present and absent
- A source is present when it supplies a value for the setting, even an empty one. It is absent when it supplies nothing at all.
- nullish coalescing (??)
- The operator a ?? b. It gives b only when a is undefined or null, so it keeps "" and 0. a || b gives b whenever a is falsy, including "" and 0.
- validation
- Checking that a value follows the rules the program needs, such as “1 to 5 digits, from 1 to 65535”, before using it.
- provenance
- A record of where a value came from: here, the name of the source that won, kept with the value and named in every error.
Build brief · one port setting
- Input
- The text of a flag, an environment variable, and a file line, each of which may be absent.
- Output
- A port number and the source it came from, or an error that names the source and its text.
- Policy
- flag, then env, then file, then the default 3000. In this program’s policy, a source that is set counts even when its value is empty. Only the winner is checked: 1 to 5 digits, 1 to 65535. An invalid winner is an error.
Examples are focused snippets; imports, enclosing functions, or classes may be omitted. C examples use C11; Haskell examples use Haskell 2010. Expand the notes for language-specific depth.
01 / Precedence
Which source wins?
A setting is one value a program needs before it can do its work, such as the port number it listens on. A setting can come from several sources: a command-line flag such as --port=7000, typed after the program’s name; an environment variable such as APP_PORT, set before the program starts; a line in a configuration file; or a default written in the program.
When several sources supply the port, the program needs a rule. Precedence is that rule: a fixed order of sources in which the first one that supplies a value wins. This program uses a common order: flag, then environment variable, then file, then the default 3000.
For now, the sources are function parameters. flag?: string declares a parameter that may be left out, and then it holds undefined; !== undefined tests that it was given.
function choose(flag?: string, env?: string, file?: string): string {
if (flag !== undefined) return flag + " from flag";
if (env !== undefined) return env + " from env";
if (file !== undefined) return file + " from file";
return "3000 from default";
} Look at the sources in precedence order and stop at the first one that supplies a value.
Precisely: the order is a choice
No language or operating system sets this order. Flag, then environment, then file, then default is a common convention, because each source is more specific to one run than the next. Some tools add more sources, such as a file per user and a file per project. Whatever the order, a program should write it down where its users can read it.
Experiment
Follow the sources from the highest
choose tests the sources in precedence order, highest first, and returns at the first one that is present. An absent source is skipped. Once a source is found, the lower ones are never looked at.
Why it matters When a setting surprises you, follow the same order by hand. The first source that is present is the one that won.
Predict which source wins before running. Then make the environment variable absent too, by changing "5000" in the call to undefined, and predict again.
function choose(flag?: string, env?: string, file?: string): string {
if (flag !== undefined) return flag + " from flag";
if (env !== undefined) return env + " from env";
if (file !== undefined) return file + " from file";
return "3000 from default";
}
const port = choose(undefined, "5000", "4100");
console.log(port);
What to look for
Step into choose and watch which line returns. flag shows undefined, so the first if does not return; env shows "5000", so the second one does. Back at the top level, port shows "5000 from env". After the edit, env shows undefined too, the third if returns, and the run prints 4100 from file. The top-level frame also lists choose, shown as function choose(flag, env, file): the panel lists a declared function as a variable, by its name and parameters. Step sometimes stops on the same line two or three times; that is normal for this debugger.
Expected output
5000 from env02 / Presence
Is an empty value the same as a missing one?
A source is present when it supplies a value, and absent when it supplies nothing. Starting a program with APP_PORT set to "" sets the variable, to an empty value. In this program’s policy, a source that is set counts even when its value is empty: someone set it, so the program checks that empty value and reports an error, instead of moving on to the next source. Some tools choose the other policy and treat an empty variable as not set; either is fine if the documentation says which.
process.env, which holds the environment variables in Node.js, is an object whose values are strings, or undefined for a name that is not set. Programs often write process.env.APP_PORT || "3000". || gives its right side whenever its left side is falsy, and "" is falsy, so || treats an empty value as missing. ?? gives its right side only for undefined or null, so it keeps "".
const env: Record<string, string | undefined> = { APP_PORT: "" };
const withOr = env.APP_PORT || "3000"; // "3000"
const withNullish = env.APP_PORT ?? "3000"; // "" Test presence with !== undefined or ??, not with || or a plain if.
Coming from Python: os.environ.get("APP_PORT") or "3000" has the same problem, because "" is falsy in Python too.
Precisely: what happens to the empty value next
Here the empty value wins and then fails the check in the next section, so the person sees an error that names APP_PORT and shows its text as "".
Experiment
Tell an empty value from a missing one
|| gives its right side when its left side is falsy, and "" is falsy, so || treats an empty value like a missing one. ?? gives its right side only when its left side is undefined or null, so it keeps "".
Why it matters Choose a source with ?? or !== undefined. Leave an empty value for the check, which can report it.
Predict both values in brackets before running. Then change { APP_PORT: "" } to {} and predict again.
// Stands in for process.env: each value is a string or undefined.
const env: Record<string, string | undefined> = { APP_PORT: "" };
const withOr = env.APP_PORT || "3000";
const withNullish = env.APP_PORT ?? "3000";
console.log("[" + withOr + "] [" + withNullish + "]");
What to look for
Step past each line and compare withOr and withNullish. env shows {APP_PORT: ""}. withOr shows "3000" and withNullish shows "", and the run prints [3000] []. After the edit, env shows {}, both show "3000", and the run prints [3000] [3000].
Expected output
[3000] []03 / Validation
What if the winning value is not a port?
The chosen value is still text. Before the program uses it as a port, validation checks the text against the program’s own rule: one to five ASCII digits (the characters 0 to 9), and a number from 1 to 65535. Leading zeros are allowed, so 00080 means 80.
Number() is not that rule. It turns "" into 0, " 80" into 80, "1e3" into 1000, and "80x" into NaN, the number value that means “not a number”. So the program checks the characters first and converts afterwards. /^[0-9]{1,5}$/ is a pattern: ^ and $ mark the start and the end, and [0-9]{1,5} means one to five characters from 0 to 9. test returns true when the whole text matches.
When the winning value fails the check, the program could fall through to the next source or stop with an error. This program stops. If the flag says 80x, the person asked for a port on this run. Using the environment’s 5000 instead, with no error, would start the program on a port the person did not ask for.
// Inside load, once source and raw are chosen:
const where = source + ' "' + raw + '"';
if (!/^[0-9]{1,5}$/.test(raw)) {
return { ok: false, error: where + " is not 1 to 5 digits" };
}
const port = Number(raw);
if (port < 1 || port > 65535) {
return { ok: false, error: where + " is not between 1 and 65535" };
} Check the value that won. If it fails, report an error; do not try the next source.
Coming from Python: int("80x") raises ValueError and stops the program. Number("80x") returns NaN without complaint, and NaN || 3000 is 3000, so nothing stops it.
Precisely: why check the characters first
Number also accepts "0x50" (80, written in hexadecimal) and "Infinity", and parseInt("80x", 10) returns 80 and ignores the x. Checking the characters first means every text that reaches Number is five digits or fewer, which Number converts exactly.
Experiment
Give the parser a value that is not a port
Number("80x") is NaN, the number value that means “not a number”. NaN is falsy, so || replaces it with 3000, and nothing reports the problem. ?? keeps NaN, because NaN is not undefined or null. Neither operator checks that the text is a port.
Why it matters Check the text with your own rule before you convert it. When the chosen value fails, report an error; do not swap in another value.
Predict the printed line before running. Then change || 3000 to ?? 3000 and predict again.
function load(flag?: string, env?: string): string {
let raw = "3000";
let source = "default";
if (env !== undefined) { raw = env; source = "env"; }
if (flag !== undefined) { raw = flag; source = "flag"; }
const port = Number(raw) || 3000;
return port + " from " + source;
}
console.log(load("80x", "5000"));
What to look for
Step through load and watch raw and source. They start as "3000" and "default", change to the env values, and then to "80x" and "flag". Then port shows 3000, and the run prints 3000 from flag: the line says the flag chose a port that really came from the default. After the edit, port shows NaN, and the run prints NaN from flag.
Expected output
3000 from flag04 / Provenance
How does the program say where a value came from?
Provenance is a record of where a value came from. The program keeps it by returning the source with the port, and by putting the source and the raw text in every error. Then error: flag "80x" is not 1 to 5 digits tells the person which of the four places to fix.
The result has two shapes: { ok: true, … } holds a port and its source, and { ok: false, … } holds an error message. A type like this, whose shapes are told apart by one property, is called a discriminated union. TypeScript lets the code read result.port only after it has checked result.ok.
type Loaded =
| { ok: true; port: number; source: string }
| { ok: false; error: string };
const result: Loaded = { ok: true, port: 5000, source: "env" };
if (result.ok) console.log(result.port + " from " + result.source); Return the source with the value, and name the source and the raw text in every error.
Precisely: showing every setting at start
Many tools can print each setting with the place it came from; git config --list --show-origin is one example. A function that already returns the source makes that a few lines of code.
05 / Real sources
Where do the real flags, variables, and files come in?
A real program reads its sources from outside. In Node.js, process.argv holds the words of the command line, process.env holds the environment variables, and the node:fs module reads files. Each gives text, or undefined when something is missing.
Keep those reads in one place, at the start of the program. That code collects the text and passes it to load; load itself reads nothing from outside. Then you can call load with any combination of sources, as the experiments and the program on this page do.
The stepper on this page always starts a program without flags, and with an environment you cannot change. So this lesson passes the sources as arguments. The choosing and checking code is the code a real program would run; only the place the text comes from is a stand-in.
// The start of a real program; not run on this page.
let flag: string | undefined;
for (const word of process.argv.slice(2)) {
if (word.startsWith("--port=")) flag = word.slice("--port=".length);
}
const result = load(flag, process.env.APP_PORT, undefined); Read the command line, the environment, and files in one place, and pass plain values to the code that decides.
Coming from Python: process.env is like os.environ, but reading a name that is not set gives undefined instead of raising KeyError.
Precisely: the command line
process.argv starts with the path of node and the path of the script, so slice(2) keeps only the words after them. A real tool usually uses a parser such as parseArgs from node:util, which also handles --port 7000 with a space and prints help. In front-end code built by Vite, import.meta.env plays the part of process.env, with values fixed when the app is built. The file is left as undefined here; reading one is a separate topic in this module, Files, parsing, and serialization.
06 / Try it
Can you predict the winner and the outcome?
The workbench below is a model of this lesson’s policy that runs in your browser. It does not run TypeScript code or read your environment. It draws the sources in the reverse of this lesson’s order: flag, the highest source, is at the right end. So the winner is the source furthest to the right that is present.
Predict the result before each change: turn off flag; turn off env as well; turn flag back on and clear its text; then type broken into file while flag holds 7000.
The flag is absent, APP_PORT is set to 0080, and the file says 70000. What does the program report, and why?
Reveal the reasoning
80 from env. The environment variable is the highest source that is present. 0080 is four digits, and leading zeros are allowed, so it gives 80. The file’s 70000 would fail the range check, but the file did not win, so it is never checked.
07 / Whole program
Does the whole program follow the policy?
The complete program below joins the pieces and runs the thirteen acceptance cases, one output line each. Each case gives the flag, the environment variable, and the file, with undefined for an absent source. Copy it into a file and run it with Node.js to see the same thirteen lines.
type Loaded =
| { ok: true; port: number; source: string }
| { ok: false; error: string };
function load(flag?: string, env?: string, file?: string): Loaded {
let source = "default";
let raw = "3000";
if (flag !== undefined) {
source = "flag";
raw = flag;
} else if (env !== undefined) {
source = "env";
raw = env;
} else if (file !== undefined) {
source = "file";
raw = file;
}
const where = source + ' "' + raw + '"';
if (!/^[0-9]{1,5}$/.test(raw)) {
return { ok: false, error: where + " is not 1 to 5 digits" };
}
const port = Number(raw);
if (port < 1 || port > 65535) {
return { ok: false, error: where + " is not between 1 and 65535" };
}
return { ok: true, port: port, source: source };
}
// Each case is [flag, env, file]; undefined means absent.
const cases: (string | undefined)[][] = [
["7000", "5000", "4100"],
[undefined, "5000", "4100"],
[undefined, undefined, "4100"],
[undefined, undefined, undefined],
["", "5000", undefined],
["80x", "5000", undefined],
[" 80", undefined, undefined],
["+80", undefined, undefined],
["0", undefined, undefined],
["65536", undefined, undefined],
["7000", undefined, "broken"],
["00080", undefined, undefined],
[undefined, "", "4100"],
];
for (const [flag, env, file] of cases) {
const result = load(flag, env, file);
if (result.ok) console.log(result.port + " from " + result.source);
else console.log("error: " + result.error);
}
Acceptance cases
- flag 7000, env 5000, file 41007000 from flag
- no flag; env 5000, file 41005000 from env
- only file 41004100 from file
- no flag, env, or file3000 from default
- flag "" (set, but empty), env 5000error: flag "" is not 1 to 5 digits
- flag 80x, env 5000error: flag "80x" is not 1 to 5 digits
- flag " 80" (a space first)error: flag " 80" is not 1 to 5 digits
- flag +80error: flag "+80" is not 1 to 5 digits
- flag 0error: flag "0" is not between 1 and 65535
- flag 65536error: flag "65536" is not between 1 and 65535
- flag 7000, file broken7000 from flag; the file is never checked
- flag 0008080 from flag
- env "" (set, but empty), file 4100error: env "" is not 1 to 5 digits
What does this program settle, and what does it leave out?
Reveal the reasoning
It settles one setting: which source wins, whether its text is a port, and how to say where it came from. It does not read a real command line, environment, or file, check settings that did not win, or start anything on the port. Each of those is a separate piece with its own rules.
Practice tickets
- CFG-101 · Stop hiding a bad retention setting → Free
- CFG-102 · Let the last width win → Sign in · Pro
- CFG-103 · Choose the watering minutes → Sign in · Pro
Keep exploring
I/O, buffering, and external state →