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


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.

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.

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.

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.

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.

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