Cannot read Property 'toLocaleString' of Undefined in JS


Borislav Hadzhiev

Wed Oct 20 20212 min read

Cannot read Property 'toLocaleString' of Undefined #

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

cannot read property tolocalestring of undefined

Here is an example of how the error occurs.

const example = undefined; // ⛔️ Cannot read properties of undefined (reading 'toLocaleString') example.toLocaleString('en-US');

Instead, you can provide the fallback for the value before calling the toLocaleString() method or check if the value is of the correct type.

const example = undefined; // ✅ Using optional chaining ?. const result1 = example?.toLocaleString('en-US') || ''; console.log(result1); // 👉️ ""

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 undefined or null, otherwise it calls the toLocaleString() 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 toLocaleString() method.

const example = undefined; if (example) { const result = example.toLocaleString('en-US'); }

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 a ternary operator to achieve the same result.

const example = undefined; const result = example ? example.toLocaleString('en-US') : ''; 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.