How to fix TypeError: Cannot read properties of undefined
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
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