TypeScript Array toLocaleString()
Syntax & Examples
Array.toLocaleString() method
The toLocaleString() method returns a string representing the elements of the array. The elements are converted to strings using their toLocaleString methods and are separated by a locale-specific string.
Syntax of Array.toLocaleString()
The syntax of Array.toLocaleString() method is:
toLocaleString(): string
This toLocaleString() method of Array returns a string representation of an array. The elements are converted to string using their toLocaleString methods.
Return Type
Array.toLocaleString() returns value of type string
.
✐ Examples
1 Using toLocaleString() on a numeric array
The toLocaleString() method can be used to convert a numeric array to a locale-specific string representation.
For example,
- Create an array
arr
with numeric values [1000, 2000, 3000]. - Use
toLocaleString()
to convert the array to a locale-specific string. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = [1000, 2000, 3000];
const result = arr.toLocaleString();
console.log(result);
Output
1,000,2,000,3,000
2 Using toLocaleString() on a date array
The toLocaleString() method can be used to convert an array of Date objects to a locale-specific string representation.
For example,
- Create an array
arr
with Date objects. - Use
toLocaleString()
to convert the array to a locale-specific string. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = [new Date('2024-01-01'), new Date('2024-12-31')];
const result = arr.toLocaleString();
console.log(result);
Output
1/1/2024, 12/31/2024
3 Using toLocaleString() on a mixed array
The toLocaleString() method can be used to convert an array with mixed types to a locale-specific string representation.
For example,
- Create an array
arr
with mixed values [12345.67, new Date('2024-01-01'), true]. - Use
toLocaleString()
to convert the array to a locale-specific string. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = [12345.67, new Date('2024-01-01'), true];
const result = arr.toLocaleString();
console.log(result);
Output
12,345.67, 1/1/2024, true
Summary
In this TypeScript tutorial, we learned about toLocaleString() method of Array: the syntax and few working examples with output and detailed explanation for each example.