Borislav Hadzhiev
Thu Oct 21 2021·3 min read
Photo by Filipp Nekhaev
The "Cannot read property 'name' of undefined" error occurs when accessing the
name
property on an undefined
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 = undefined; // ⛔️ Cannot read properties of undefined (reading 'name') obj.name;
To solve the error make sure to only access the name
property on objects.
const obj = undefined; // ✅ Using optional chaining const result1 = obj?.name; console.log(result1); // 👉️ undefined // ✅ Using ternary operator const result2 = obj ? obj.name : undefined; console.log(result2); // 👉️ undefined // ✅ 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 undefined
or null
.
If the value stored in the obj
variable is equal to undefined
or null
, 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
, undefined
, null
, 0
, ""
(empty string), NaN
(not a number).
Alternatively, you can provide a fallback value when declaring the object.
const fromDb = undefined; 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. undefined
).
Other Common reasons the "Cannot read property 'name' of undefined" error occurs are:
Here's an example that shows the error being thrown when using arrays.
const arr = []; // 👇️ Cannot read properties of undefined (reading 'name') arr[0].name();
To solve this, you have to make sure the element at the index is available and an object.
const arr = []; const result = arr?.[0]?.name || ''; console.log(result); // 👉️ ""
We used the optional chaining operator to short-circuit if either reference is
equal to undefined
or null
and provided an empty string fallback to make
sure we return a string from the operation.
If using classes, you have to declare the class property and set it to an empty object before accessing it.
class Person { // ✅ Initialize from parameters constructor(data) { this.data = data; } getName() { return this.data.name; } } const p1 = new Person({name: 'John Smith'}); console.log(p1.getName()); // 👉️ "John Smith"
We initialized the values for the data
class property. Had we not done that,
we would get the error when trying to access the property.
The "Cannot read property 'name' of undefined" error occurs when accessing the
name
property an undefined
value.
To solve the error, make sure to only access the property on objects.