erradicate

How to fix TypeError: Cannot read properties of undefined

Technologies
webnode.js
Variants
  • TypeError: Cannot read properties of null (Chrome, Node.js)
  • TypeError: foo is undefined (Firefox)
  • TypeError: foo is null (Firefox)

Description

While some error messages can be unhelpful, in this particular case it is straightforward - you are trying to access (read or set) a property from an object, but that object is undefined (or null).

Examples

let foo;
  console.log(foo); // undefined
  foo.bar; // TypeError: Cannot read properties of undefined

Solutions

In the simple case where the object is declared but is not assigned, simply create the object first with the object literal syntax:

let foo = {};

  foo.bar; // no error
Note: If the variable hasn't been declared at all (ex. a typo in the name), you will see a different error message.

Alternatively, if the object might not have a value for legitimate reasons, defensively check that the value exists before accessing properties off the object:

// foo is already declared but is sometimes null or undefined
  foo && foo.bar; // no error