Prompt
Always verify that an object and its properties exist before accessing them to prevent “cannot read property of undefined/null” errors. This is especially important when dealing with objects that might come from different build environments (dev vs. production) or third-party libraries.
There are two common approaches:
- Using a falsy check when null and undefined are both invalid:
if (!obj)orif (!obj.property) - Using explicit checks when you need to distinguish between different falsy values:
if (obj === undefined)orif (obj.property === null)
Example - Before:
// Risky code that might fail
clonedElement._store.validated = oldElement._store.validated;
Example - After:
// Safe code that checks existence first
if (oldElement._store && clonedElement._store) {
clonedElement._store.validated = oldElement._store.validated;
}
This is particularly important in codebases where:
- Components might be rendered in both development and production environments
- You’re integrating with third-party libraries that might have different property structures
- Properties might be conditionally added to objects
Being proactive about property existence checks leads to more robust code and prevents unexpected runtime errors.