Defensive Programming in JavaScript
Defensive programming checks inputs at boundaries, fails early with clear errors and avoids silent coercion. See practical JavaScript guards and when to stop.

Defensive programming is writing code that expects inputs, the environment and even callers to be wrong sometimes, and that makes the wrongness visible early and clearly. JavaScript needs it more than most languages, because it will coerce almost anything into something else and carry on, so a bad value can travel a long way before it causes damage. This post covers practical defenses on Node.js 24: validating at boundaries, failing fast with useful errors, avoiding silent coercion, guarding object access, handling the cases that arrive in production and not in tests, and the balance that keeps defensive code from turning into noise.
Silent failure is the enemy
Look at what JavaScript does with a mistake.
function total(prices) {
return prices.reduce((sum, p) => sum + p, 0);
}
console.log(total([10, 20, 30]));
console.log(total(["10", "20", "30"]));
console.log(total([10, undefined, 30]));60
0102030
NaNThe second call did not fail. The starting value is the number 0, and adding a string to a number concatenates, so the "total" is the string "0102030". The third call produced NaN, which then spreads through every calculation it touches. Neither call threw, and the bad value would surface later, in a display, a database column or an invoice, far from the cause.
The goal of defensive programming is to move the failure to the point where the mistake was made.
Validate at the boundary
Decide where untrusted data enters your program: HTTP requests, files, environment variables, message queues, command-line arguments and the return values of other people's libraries. Check it there, once, thoroughly. Inside that boundary, code can rely on what was checked, and stay free of repeated tests.
function sum(prices) {
prices.forEach((p, i) => {
if (typeof p !== "number" || !Number.isFinite(p)) {
throw new TypeError(
`prices[${i}] must be a finite number, got ${typeof p} (${String(p)})`,
);
}
});
return prices.reduce((s, p) => s + p, 0);
}
console.log(sum([10, 20, 30]));
for (const input of [["10", "20"], [10, undefined], [1, NaN]]) {
try {
sum(input);
} catch (err) {
console.log(err.message);
}
}60
prices[0] must be a finite number, got string (10)
prices[1] must be a finite number, got undefined (undefined)
prices[1] must be a finite number, got number (NaN)The messages name the argument, the index and what was found. That is the difference between a two-minute fix and an hour with a debugger. Number.isFinite rejects NaN and Infinity, and the typeof check rejects numeric strings, since the global isFinite("10") would accept them by coercing.
Fail fast, with the evidence
An error should say what was expected, what arrived and where. Include the offending value, shortened if it may be large. Use the right error class: TypeError for the wrong type, RangeError for a value out of bounds, and a custom class for domain failures that callers need to catch by type. When you wrap a lower-level error, keep the original through the cause option, so the stack of the root problem is not lost.
function loadConfig(text) {
try {
return JSON.parse(text);
} catch (err) {
throw new Error("invalid config file", { cause: err });
}
}
try {
loadConfig("{bad json");
} catch (err) {
console.log(err.message, err.cause.name);
}invalid config file SyntaxErrorCallers see a message about their configuration, and logs can still show the underlying SyntaxError with its position. The failure happens at startup, when the file is read, and not an hour later when a missing setting is first needed.
Avoid silent coercion
Most JavaScript surprises come from automatic conversion. A few habits remove most of them. Use === and !==, never ==, except for the deliberate value == null test for "null or undefined". Convert on purpose, with strict parsing, and not with the permissive built-ins. parseInt stops at the first character it does not understand and Number("") returns 0, so neither is a validator.
console.log(parseInt("12px", 10), Number("12px"), Number(""), Number(" "));
function parseIntStrict(text) {
if (typeof text !== "string" || !/^-?\d+$/.test(text)) {
throw new TypeError(`not an integer: ${JSON.stringify(text)}`);
}
const n = Number(text);
if (!Number.isSafeInteger(n)) throw new RangeError(`out of safe range: ${text}`);
return n;
}
console.log(parseIntStrict("42"));
for (const input of ["12px", "", "99999999999999999999"]) {
try {
parseIntStrict(input);
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
}12 NaN 0 0
42
TypeError: not an integer: "12px"
TypeError: not an integer: ""
RangeError: out of safe range: 99999999999999999999The first line shows the problem with the built-ins: parseInt accepts "12px" and returns 12, and Number treats an empty or blank string as zero. The strict version accepts only digits, with an optional minus sign, and rejects integers beyond Number.MAX_SAFE_INTEGER, which cannot be represented exactly. Environment variables, query strings and form fields all arrive as strings, so this function earns its place.
Guard object access
Objects in JavaScript inherit properties, which makes plain objects poor dictionaries for user-controlled keys.
const lookup = { a: 1 };
console.log("toString" in lookup, Object.hasOwn(lookup, "toString"));
const safe = new Map([["a", 1]]);
console.log(safe.has("toString"));true false
falseThe in operator reports true for toString, because it walks the prototype chain. Object.hasOwn checks only the object's own keys, and a Map has no inherited keys at all. For data keyed by user input, such as counting words or grouping by name, a Map avoids a family of bugs, including prototype pollution through keys such as __proto__.
Optional chaining, a?.b?.c, handles absent intermediate values without throwing. Use it for values that may legitimately be missing, not to hide values that should always be there. Writing user?.profile?.name when every user has a profile turns a clear crash into a silent undefined.
Make impossible states loud
A switch over a set of known values should say what to do with an unknown one. A missing default means a new value, added later, falls through and returns undefined.
function label(status) {
switch (status) {
case "open":
return "Open";
case "closed":
return "Closed";
default:
throw new Error(`unhandled status: ${status}`);
}
}
console.log(label("open"));
try {
label("archived");
} catch (err) {
console.log(err.message);
}Open
unhandled status: archivedWhen a developer adds "archived" to the data and forgets this function, the first run shows the omission, with the value that caused it. In TypeScript, a never check in the default branch turns the same mistake into a compile error.
Do not swallow errors in the name of safety
Defensive code can go wrong in the opposite direction, by catching every error and returning a default. That hides the problem instead of surfacing it.
function getPortBad(env) {
try {
return parseIntStrict(env.PORT);
} catch {
return 3000;
}
}
function getPort(env) {
if (env.PORT === undefined) return 3000;
return parseIntStrict(env.PORT);
}
console.log(getPortBad({ PORT: "80x" }));
console.log(getPort({}));
try {
getPort({ PORT: "80x" });
} catch (err) {
console.log(err.message);
}3000
3000
not an integer: "80x"The first version quietly ignores a misconfigured port and listens on 3000, so the operator who typed 80x wonders why nothing answers on the port they meant. The second applies the default only when the variable is absent, and reports a bad value. The rule is that a default is for "not provided", and an error is for "provided and wrong".
Handle the world, not only your inputs
Inputs are not the only thing that can be wrong. Defensive code also plans for slow and failing dependencies, and limits on what it will accept.
Time limits. Calls to other systems get a deadline, using
AbortSignal.timeout(ms)withfetch, so a hung server cannot hang your process.Size limits. Cap the size of request bodies, uploads and arrays you build from input. An unbounded input is a memory problem waiting for someone to find it.
Cleanup. Use
tryandfinallyfor anything that must be released: file handles, locks, temporary files. Afinallyblock runs whether the code threw or not.Unhandled rejections. A promise that rejects with nobody listening ends the Node.js process by default. Await every promise you create, or attach a handler on purpose.
function readLimited(items, max = 1000) {
if (!Array.isArray(items)) throw new TypeError("items must be an array");
if (items.length > max) throw new RangeError(`too many items: ${items.length} (max ${max})`);
return items.length;
}
console.log(readLimited([1, 2, 3]));
try {
readLimited(new Array(5000).fill(0));
} catch (err) {
console.log(err.message);
}3
too many items: 5000 (max 1000)Assertions for assumptions
Some checks are about your own code and not about input: "this list is never empty at this point". Express them as assertions, which document the assumption and fail loudly if it breaks. Node's assert module provides them, and in strict mode assert.ok and assert.equal use strict comparison.
import assert from "node:assert/strict";
function first(items) {
assert.ok(items.length > 0, "first() needs a non-empty list");
return items[0];
}
console.log(first(["a", "b"]));
try {
first([]);
} catch (err) {
console.log(err.name, err.message);
}a
AssertionError first() needs a non-empty listAssertions are for programmer errors. Input from outside should produce an ordinary validation error that you handle, not an assertion that means a bug.
Where to stop
Defensive code has a cost. Every check is code to read and maintain, and a function that validates every argument at every layer repeats itself and buries its purpose. Aim for a clear boundary, thorough checking there, and trust inside. Private helpers called only from validated code need not recheck. Do not defend against impossible states in a way that hides real bugs, and do not add a check you cannot explain with a concrete failure.
TypeScript moves some of this to compile time, where it is free: required parameters, union types and readonly data. It does not remove the need to check data from outside the program, because types are erased at run time. Use both: types for your own code, validation at the edge.
Testing the defenses
Test the failure paths as carefully as the success paths. Each guard is a promise that bad input produces a specific error, and a test is how you keep the promise.
import assert from "node:assert/strict";
import { test } from "node:test";
test("sum rejects a numeric string with a precise message", () => {
assert.throws(() => sum(["10"]), {
name: "TypeError",
message: "prices[0] must be a finite number, got string (10)",
});
});
test("getPort uses the default only when the variable is missing", () => {
assert.equal(getPort({}), 3000);
assert.throws(() => getPort({ PORT: "abc" }), /not an integer/);
});✔ sum rejects a numeric string with a precise message (1.2ms)
✔ getPort uses the default only when the variable is missing (0.3ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

