0Pricing
JavaScript Academy · Lesson

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
Defensive Programming & Input Checks — illustration 1

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"));
Defensive Programming & Input Checks — illustration 2

All lessons in this course

  1. try/catch/finally, throw, custom errors
  2. Defensive Programming & Input Checks
← Back to JavaScript Academy