Solve - Cannot read property 'name' of Null in JS

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

Solve - Cannot read property 'name' of Null #

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.

cannot read property name of null

Here is an example of how the error occurs.

index.js
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.

index.js
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.

If the value to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise the value to the right of the colon is returned.

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.

index.js
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).

Use the search field on my Home Page to filter through my more than 1,000 articles.