ProjectStack
npm

TypeError: Cannot read properties of null

You're trying to access a property on a variable that is explicitly null. Unlike undefined, null is intentionally set — something returned null or you set it to null yourself.

Common causes

  • document.getElementById() or querySelector() returned null because the element doesn't exist
  • A database query returned null for a record that wasn't found
  • JSON.parse() parsed a 'null' literal string
  • A function explicitly returns null to indicate 'no result'

How to fix it

  1. Check for null before accessing properties: if (element !== null)
  2. Use optional chaining: element?.textContent
  3. For DOM elements, ensure the element exists in the HTML before the script runs
  4. Add fallback values: const result = getValue() ?? defaultValue

Example

TypeError: Cannot read properties of null (reading 'addEventListener') at HTMLDocument.<anonymous> (/home/user/app.js:5:40)

Calling addEventListener on document.getElementById('btn') where no element with id 'btn' exists in the HTML

Have a different error?

Paste any error message into the Error Translator to get an instant explanation.