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.

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