Defensive Programming in JavaScript

Write defensive code to prevent errors

IntermediateError HandlingExample 8 of 10
defensive-programming.js
1// Method 1: Input validation
2function processUserInput(input) {
3 if (typeof input !== 'string') {
4 throw new TypeError('Input must be a string');
5 }
6
7 if (input.length === 0) {
8 throw new Error('Input cannot be empty');
9 }
10
11 if (input.length > 100) {
12 throw new Error('Input too long');
13 }
14
15 return input.trim();
16}
17
18// Method 2: Null/undefined checks
19function safeAccess(obj, path) {
20 const keys = path.split('.');
21 let current = obj;
22
23 for (const key of keys) {
24 if (current == null) {
25 return null;
26 }
27 current = current[key];
28 }
29
30 return current;
31}
32
33const user = { profile: { name: 'John' } };
34console.log('Name:', safeAccess(user, 'profile.name'));
35console.log('Missing:', safeAccess(user, 'profile.email'));
36
37// Method 3: Default values
38function getValue(value, defaultValue) {
39 return value != null ? value : defaultValue;
40}
41
42function 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}
49
50// Method 4: Type checking
51function 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}
58
59// Method 5: Range validation
60function 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}
66
67// Method 6: Safe array operations
68function safeArrayOperation(array, index, operation) {
69 if (!Array.isArray(array)) {
70 throw new TypeError('First argument must be an array');
71 }
72
73 if (index < 0 || index >= array.length) {
74 return null;
75 }
76
77 return operation(array[index]);
78}
79
80// Method 7: Error boundaries
81function withErrorBoundary(fn, fallback) {
82 try {
83 return fn();
84 } catch (error) {
85 console.error('Error in function:', error);
86 return fallback();
87 }
88}
89
90const 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