Always perform explicit null/undefined checks before accessing properties or using values that could be null or undefined. Use strict equality checks rather than relying on JavaScript's truthy/falsy evaluation which can lead to subtle bugs.
Always perform explicit null/undefined checks before accessing properties or using values that could be null or undefined. Use strict equality checks rather than relying on JavaScript’s truthy/falsy evaluation which can lead to subtle bugs.
Common patterns to adopt:
// Bad:
if (error.code === 'AuthorizationHeaderMalformed') { /* ... */ }
// Good:
if (error && error.code === 'AuthorizationHeaderMalformed') { /* ... */ }
// Bad - indexOf returns 0 for first item which is falsy:
if (list.indexOf(member)) { return true; }
// Good:
if (list.indexOf(member) >= 0) { return true; }
// Bad:
return window.localStorage !== null;
// Good:
return AWS.util.isBrowser() && window.localStorage !== null && typeof window.localStorage === 'object';
// Bad:
function handleParams(params) {
params.property = 'value'; // Fails if params is null/undefined
}
// Good:
function handleParams(params) {
params = params || {};
params.property = 'value';
}
// Bad - fails for zero values:
if (params.$waiter.delay) {
this.config.delay = params.$waiter.delay;
}
// Good:
if (typeof params.$waiter.delay === 'number') {
this.config.delay = params.$waiter.delay;
}
Consistent null checking prevents the most common class of runtime errors and produces more predictable code.
Enter the URL of a public GitHub repository