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

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

Solve - Cannot read property 'toString' of Null #

The "Cannot read property 'toString' of null" error occurs when the toString() method is called on a null value. To solve the error, make sure to only call the toString method on data types that implement the method.

cannot read property tostring of null

Here's an example of how the error occurs.

index.js
const example = null; // โ›”๏ธ Cannot read properties of null (reading 'toString') example.toString();

To solve the error, provide a fallback for the value before calling the toString() method or check if the value is of the correct type.

index.js
const example = null; // โœ… Using optional chaining ?. const ex1 = example?.toString() || ''; console.log(ex1); // ๐Ÿ‘‰๏ธ ""

This code snippet uses the optional chaining (?.) operator to avoid getting the error.

The optional chaining (?.) operator short-circuits if the reference is equal to null or undefined, otherwise it calls the toString() method.

Notice that we also used the logical OR (||) operator to provide a fallback value of an empty string.

If the optional chaining (?.) operator short-circuits, it returns an undefined value and because we want to be consistent we return an empty string in that scenario.

You can also check if the value is truthy before calling the toString() method.

index.js
const example = null; if (example) { const result = example.toString(); }

The if condition is only satisfied if the value stored in the example 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).

You can also use a ternary operator to achieve the same result.

index.js
const example = null; const result = example ? example.toString() : ''; console.log(result); // ๐Ÿ‘‰๏ธ ""

The ternary operator is very similar to an if/else statement. It checks if the value to the left is truthy, if it is, the operator returns the value to the left of the colon, otherwise the value to the right is returned.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee