Skip to content

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() returned null because no element matched the selector

  • An API returned null for a field you expected to be an object

  • A variable was explicitly set to null and then used as an object

Minimal example

✗ Broken code
const el = document.querySelector("#missing");
el.addEventListener("click", fn);
✓ Fixed code
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 null

  • If using querySelector, verify the selector matches an element in the DOM

  • Check 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 properties

  • Provide a fallback value when the object is null

How to prevent

  • Always check querySelector results before using them

  • Use optional chaining consistently for uncertain property accesses

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language