;

Javascript Array - toLocaleString() Method


Tutorialsrack 05/11/2022 Jquery Javascript

In this article, you will learn about the Javascript Array built-in method Array.prototype.toLocaleString().  How does this method work in javascript? 

Array.prototype.toLocaleString()

The Array.prototype.toLocaleString() method is used to return a string containing all the elements of a specified array in a particular locale. This method separates them by a comma. If an element is undefined, or null, it is converted to an empty string instead of the string "null" or "undefined". When used on sparse arrays, the toLocaleString() method iterates empty slots as if they have the value undefined.

Syntax
array.toLocaleString(locale, options);

This method takes 2 parameters and both are optional:

The toLocaleString() method does not change the original array.

Using locales and options

The elements of the array are converted to strings using their toLocaleString methods.

Here are some examples of Array.prototype.toLocaleString() method:

Example 1: Using toLocaleString()

Example 1: Using toLocaleString()
const language = ["Java", "C#", "Go", "JavaScript", "Python"];

console.log(language.toLocaleString());
// Output => "Java,C#,Go,JavaScript,Python"

Example 2: Using locales and options

Example 2: Using locales and options
const prices = ['₹7', 500, 8123, 12];

console.log(prices.toLocaleString('en-IN', { style: 'currency', currency: 'INR' }));
//Output => "₹7,₹500.00,₹8,123.00,₹12.00"

Example 3: Using toLocaleString() on sparse arrays

Example 3: Using toLocaleString() on sparse arrays
console.log([1, , 3].toLocaleString()); 
//Output => '1,,3'

I hope this article will help you to understand the javascript Array built-in method Array.prototype.toLocaleString()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags