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


Borislav Hadzhiev

Last updated: Jul 25, 2022


Check out my new book

Solve - Cannot read property 'toString' of Undefined #

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

cannot read property tostring of undefined

Here is an example of how the error occurs.

const example = undefined; // ⛔️ Cannot read properties of undefined (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 = undefined; // ✅ Using optional chaining ?. const ex1 = example?.toString() || ''; console.log(ex1); // 👉️ ""

We used the optional chaining (?.) operator to avoid getting the error.

The optional chaining (?.) operator short-circuits if the reference is equal to undefined or null, 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. For consistency, we return an empty string in that scenario.

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

const example = undefined; 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, undefined, null, 0, "" (empty string), NaN (not a number).

You can also use the ternary operator to avoid getting the error.

const example = undefined; 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, and 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 3,000 articles.