TypeError: Cannot read properties of null
Error message
Cannot read properties of null (reading 'x')
Quick summary
You used dot notation on a value that is `null` — `null` has no properties, so the access fails.
Why this happens
document.querySelector()returnednullbecause no element matched the selectorAn API returned
nullfor a field you expected to be an objectA variable was explicitly set to
nulland then used as an object
Minimal example
const el = document.querySelector("#missing");
el.addEventListener("click", fn);const el = document.querySelector("#missing");
if (el) el.addEventListener("click", fn);querySelector returns null when no element matches — calling .addEventListener on null throws. Check for null first.
How to diagnose
Log the value before the property access to confirm it is
nullIf using
querySelector, verify the selector matches an element in the DOMCheck API documentation for fields that may be
null
How to fix
Add a null check before accessing the property (
if (el !== null))Use optional chaining (
el?.property) to safely access propertiesProvide a fallback value when the object is
null
How to prevent
Always check
querySelectorresults before using themUse optional chaining consistently for uncertain property accesses
Related Resources
Related Practice
- JavaScript Primitive Types
Understand primitive types including null.