Defensive Programming in JavaScript
Write defensive code to prevent errors
IntermediateError HandlingExample 8 of 10
defensive-programming.js
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);
Output
Name: John Missing: null
What's going on
Defensive programming prevents errors.
Input Validation
Check types
Validate ranges
Check required fields
Sanitize input
Null Checks
Check for null/undefined
Safe property access
Optional chaining
Default values
Type Checking
Validate types
Throw early
Clear error messages
Type guards
Range Validation
Min/max values
Array bounds
String length
Numeric ranges
Safe Operations
Array bounds
Object properties
Function calls
Error boundaries
Best Practices
Validate early
Fail fast
Provide defaults
Handle edge cases