Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Chansereypich Seng
The "Cannot read property 'name' of null" error occurs when accessing the
name
property on a null
value. To solve the error, conditionally check if
the value you're accessing the name
property on is of the expected type.
Here is an example of how the error occurs.
const obj = null; // ⛔️ Cannot read properties of null (reading 'name') obj.name;
To solve the error make sure to only access the name
property on objects.
const obj = null; // ✅ Using optional chaining const result1 = obj?.name; console.log(result1); // 👉️ undefined // ✅ Using ternary operator const result2 = obj ? obj.name : ""; console.log(result2); // 👉️ "" // ✅ Using if/else if (obj) { const result3 = obj.name; } else { console.log('obj is falsy'); }
The first example uses the
optional chaining (?.)
operator to short-circuit if the reference is equal to null
or undefined
.
If the value stored in the obj
variable is equal to null
or undefined
, the
operator will return undefined
, otherwise it will access the name
property
and return the result.
The second example uses the
ternary operator,
which is very similar to an if/else
statement.
The last example uses an if/else
statement to check if the value stored in the
obj
variable is truthy.
Truthy are all the values that are not falsy.
The falsy values in JavaScript are: false
, null
, undefined
, 0
, ""
(empty string), NaN
(not a number).
Alternatively, you can provide a fallback value when declaring the object.
const fromDb = null; const obj = fromDb || {};
We used the
logical OR (||)
operator to provide an empty object as a fallback if the value to the left is
falsy (e.g. null
).