Defensive Programming in JavaScript
Learn defensive programming in JavaScript: check input, guard null values, set defaults, validate types and ranges, and use fallbacks. Explanation and output.
1// Method 1: Input validation2function processUserInput(input) {3 if (typeof input !== 'string') {4 throw new TypeError('Input must be a string');5 }67 if (input.length === 0) {8 throw new Error('Input cannot be empty');9 }1011 if (input.length > 100) {12 throw new Error('Input too long');13 }1415 return input.trim();16}1718// Method 2: Null/undefined checks19function safeAccess(obj, path) {20 const keys = path.split('.');21 let current = obj;2223 for (const key of keys) {24 if (current == null) {25 return null;26 }27 current = current[key];28 }2930 return current;31}3233const user = { profile: { name: 'John' } };34console.log('Name:', safeAccess(user, 'profile.name'));35console.log('Missing:', safeAccess(user, 'profile.email'));3637// Method 3: Default values38function getValue(value, defaultValue) {39 return value != null ? value : defaultValue;40}4142function processConfig(config) {43 return {44 timeout: getValue(config.timeout, 5000),45 retries: getValue(config.retries, 3),46 url: getValue(config.url, 'https://api.example.com')47 };48}4950// Method 4: Type checking51function validateType(value, expectedType) {52 const actualType = typeof value;53 if (actualType !== expectedType) {54 throw new TypeError(`Expected ${expectedType}, got ${actualType}`);55 }56 return value;57}5859// Method 5: Range validation60function validateRange(value, min, max) {61 if (value < min || value > max) {62 throw new RangeError(`Value must be between ${min} and ${max}`);63 }64 return value;65}6667// Method 6: Safe array operations68function safeArrayOperation(array, index, operation) {69 if (!Array.isArray(array)) {70 throw new TypeError('First argument must be an array');71 }7273 if (index < 0 || index >= array.length) {74 return null;75 }7677 return operation(array[index]);78}7980// Method 7: Error boundaries81function withErrorBoundary(fn, fallback) {82 try {83 return fn();84 } catch (error) {85 console.error('Error in function:', error);86 return fallback();87 }88}8990const result = withErrorBoundary(91 () => riskyOperation(),92 () => 'Default value'93);
Sample Output
Missing: undefined
profile exists, so the loop does not return null. It reads profile.email, which is undefined.
Error in function: ReferenceError: riskyOperation is not defined
riskyOperation was never written, so the call throws. The boundary catches it and result becomes "Default value".
In this one
- How to check input before using it
- How to read nested values safely
- How defaults work with != null and ??
- How a fallback wrapper keeps the app running
How it works
- 1
safeAccess reads profile.name and prints John.
- 2
safeAccess reads profile.email and prints undefined.
- 3
withErrorBoundary calls riskyOperation.
- 4
A ReferenceError is caught and logged.
- 5
The fallback returns Default value.
Edge cases
Using || for defaults
config.retries || 3 turns 0 into 3.
Use ?? or != null so 0 stays 0.
NaN passes range checks
validateRange(NaN, 0, 10) does not throw.
Check Number.isFinite(value) first.
Too many checks
Every inner function repeats the same checks.
Validate at the edges, where data enters the app.
What's going on
Defensive programming means writing code that expects bad input and handles it calmly. You check values before using them, so problems are found early with a clear message. In JavaScript this matters because types are loose and values can be missing.
Method 1 validates input. It checks the type, the empty case and the length before doing any work. Each check throws a clear error, like "Input must be a string". A TypeError means a value has the wrong type.
Method 2 is safeAccess. It walks a path like 'profile.name' one key at a time. If a step is null or undefined, it stops and returns null. For 'profile.email' the profile exists but has no email, so the result is undefined, not null. The null return only happens when a middle step is missing. Today you can write user?.profile?.email with optional chaining for the same job.
Method 3 gives default values. value != null is true for anything except null and undefined, so 0 and an empty string are kept. The ?? operator does the same in modern JavaScript.
Methods 4 and 5 check the type and the range. A RangeError means a number is outside the allowed range. Method 6 checks that the value is an array and the index is inside it before using it.
Method 7 runs a function inside try and returns a fallback on failure. In this sample riskyOperation does not exist, so calling it throws a ReferenceError. The boundary catches it, logs it and returns 'Default value'. That shows the boundary working.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does getValue(0, 5) return?
Pick an answer to check it.
Question 2
What does safeAccess(user, "profile.email") return here?
Pick an answer to check it.
Questions people ask
Is optional chaining better than safeAccess?
For fixed paths, yes. safeAccess helps when the path is a string.
Where should I validate?
Where data comes in: forms, API replies and function inputs from other modules.
Why does typeof null say object?
It is an old JavaScript bug. Check value === null directly.