Cannot read properties of null
An attempt was made to read a property or call a method on a null object.
Usually happens because:
- ☑ querySelector failed to find element
- ☑ API returned null object
- ☑ Variable explicitly set to null
🔍 Quick Checklist:
📊 Where this usually happens (estimated occurrence)
What is Cannot read properties of null?
This error is thrown when you attempt to access a property or invoke a method on a variable that evaluates to null. While null represents an intentional absence of any object value, it has no keys or attributes. Querying null.someProperty or null.toString() triggers a TypeError.
Common Causes
- Querying DOM elements that do not exist (document.querySelector returns null).
- Parsing database queries or API payloads that return null values for empty fields.
- Explicitly setting variables to null and accessing properties later without resetting them.
Common Mistakes
- Binding event listeners inside head scripts before the DOM structure is fully loaded by the browser.
- Accessing database records that have nullable columns without adding fallback checks.
How to Fix
Framework-Specific Examples
Failing to verify if elements exist in the active document scope before binding event listeners.
const btn = document.querySelector("#non-existent-btn");
try {
btn.addEventListener("click", () => {}); // btn is null, throwing TypeError
} catch (err) {
console.error(err.message); // Cannot read properties of null (reading 'addEventListener')
}Server Configuration Examples
Scanning incoming JSON bodies for null properties to prevent downstream crashes.
app.post('/update', (req, res) => {
const settings = req.body.settings;
if (settings === null) {
return res.status(400).json({ error: 'Settings object cannot be null.' });
}
res.send('Success');
});Best Practices
- Always query DOM elements inside DOMContentLoaded callbacks.
- Implement guards (e.g. if (element !== null)) before calling element methods.
Frequently Asked Questions (FAQ)
Q: Why does querySelector return null?
Because no element matches the specified selector in the active document. Double-check your spelling, query tags, or verify that the script is executed after the elements are fully rendered.
Q: What's the difference between null and undefined?
Null is an assigned value representing the intentional absence of an object. Undefined means that a variable name has been declared but has no value associated with it yet.
Q: How do I check for null?
Use strict equality: `if (variable === null)`. Avoid using loose equality `variable == null` if you need to distinguish between null and undefined.
Q: Can I set default values for null?
Yes. You can use the logical OR operator (`const x = y || default`) or nullish coalescing (`const x = y ?? default`) to supply fallbacks.