Defensive Programming & Input Checks
Write small input checks, use guard clauses, safe parsing, defaults, and simple object validation to prevent failures early.
Intro to defensive checks
Goal: Stop bad inputs early so bugs do not spread.
- Type and range checks
- Guard clauses
- Safe parsing
- Defaults and simple object validation

Type helpers
Create small helpers to reuse checks like number and non-empty string.
// Tiny type helpers
function isNumber(n) {
return typeof n === "number" && Number.isFinite(n);
}
function isNonEmptyString(s) {
return typeof s === "string" && s.trim().length > 0;
}
console.log("isNumber(3):", isNumber(3));
console.log("isNumber(NaN):", isNumber(NaN));
console.log("isNonEmptyString(\"\"):", isNonEmptyString(""));
console.log("isNonEmptyString(\"hi\"):", isNonEmptyString("hi"));

All lessons in this course
- try/catch/finally, throw, custom errors
- Defensive Programming & Input Checks