Defensive Programming
Write defensive code to prevent errors
JavaScript Defensive Programming Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Input validation
function processUserInput(input) {
if (typeof input !== 'string') {
throw new TypeError('Input must be a string');
}
if (input.length === 0) {
throw new Error('Input cannot be empty');
}
if (input.length > 100) {
throw new Error('Input too long');
}
return input.trim();
}
// Method 2: Null/undefined checks
function safeAccess(obj, path) {
const keys = path.split('.');
let current = obj;
for (const key of keys) {
if (current == null) {
return null;
}
current = current[key];
}
return current;
}
const user = { profile: { name: 'John' } };
console.log('Name:', safeAccess(user, 'profile.name'));
console.log('Missing:', safeAccess(user, 'profile.email'));
// Method 3: Default values
function getValue(value, defaultValue) {
return value != null ? value : defaultValue;
}
function processConfig(config) {
return {
timeout: getValue(config.timeout, 5000),
retries: getValue(config.retries, 3),
url: getValue(config.url, 'https://api.example.com')
};
}
// Method 4: Type checking
function validateType(value, expectedType) {
const actualType = typeof value;
if (actualType !== expectedType) {
throw new TypeError(`Expected ${expectedType}, got ${actualType}`);
}
return value;
}
// Method 5: Range validation
function validateRange(value, min, max) {
if (value < min || value > max) {
throw new RangeError(`Value must be between ${min} and ${max}`);
}
return value;
}
// Method 6: Safe array operations
function safeArrayOperation(array, index, operation) {
if (!Array.isArray(array)) {
throw new TypeError('First argument must be an array');
}
if (index < 0 || index >= array.length) {
return null;
}
return operation(array[index]);
}
// Method 7: Error boundaries
function withErrorBoundary(fn, fallback) {
try {
return fn();
} catch (error) {
console.error('Error in function:', error);
return fallback();
}
}
const result = withErrorBoundary(
() => riskyOperation(),
() => 'Default value'
);Name: John Missing: null
Understanding Defensive Programming
Defensive programming prevents errors.
Input Validation
Null Checks
Type Checking
Range Validation
Safe Operations
Best Practices
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.
Practical Learning Notes for Defensive Programming
This JavaScript program is part of the "Error Handling" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.