Implement robust null and undefined handling patterns to prevent runtime errors and maintain code reliability. Use optional chaining for safe property access, explicit null checks with early returns, and conditional property assignment to avoid unintended undefined values.
Implement robust null and undefined handling patterns to prevent runtime errors and maintain code reliability. Use optional chaining for safe property access, explicit null checks with early returns, and conditional property assignment to avoid unintended undefined values.
Key patterns to follow:
?.
) when accessing properties that might be undefined: if (options?.throwIfNoEntry === true)
if (!webContents) return null;
Example implementation:
// Good: Optional chaining and explicit null check
const archive = getOrCreateArchive(asarPath);
if (!archive) {
if (options?.throwIfNoEntry === true) {
throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
}
return null;
}
// Good: Conditional property assignment to preserve defaults
const urlLoaderOptions = {
priority: options.priority
};
if ('priorityIncremental' in options) {
urlLoaderOptions.priorityIncremental = options.priorityIncremental;
}
This approach prevents silent failures, maintains type safety, and ensures predictable behavior when dealing with nullable values.
Enter the URL of a public GitHub repository