Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript
locale string
array
communitycreator

What is array.toLocaleString() in TypeScript?

Theodore Kelechukwu Onyejiaku

Overview

In TypeScript, we can get the string representation of an array in your locale. The locale here means the format in which our computer will display such a string.

This can be achieved by using the toLocaleString() method.

Syntax

array.toLocaleString()
Syntax for toLocaleString() method in TypeScript

Parameters

array: This is the array we want to get the string representation for.

Return value

The value returned is a string that represents the elements of the array.

Example

// create arrays in TypeScript
let names: string[] = ["Theodore", "James", "Peter", "Amaka"]
let numbers : Array<number>; 
numbers = [12, 34, 5, 0.9]
let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]
let randomValues : Array<string | number> = ["one",1, "two", 2, 56]

// get the arrays as strings
let localeStr1 = names.toLocaleString()
let localeStr2 = numbers.toLocaleString()
let localeStr3 = cars.toLocaleString()
let localeStr4 = randomValues.toLocaleString()

// print the arrays as locale strings
console.log(localeStr1, typeof(localeStr1))
console.log(localeStr2, typeof(localeStr2))
console.log(localeStr3, typeof(localeStr3))
console.log(localeStr4, typeof(localeStr4))
Get an array as a locale string in TypeScript using toLocaleString()

Explanation

  • Lines 2–6: We create arrays in TypeScript.
  • Lines 9–12: We get the string representations of the arrays using the toLocaleString() method.
  • Lines 15–18: We log out the locale strings we got, as well as the type of strings we got, to the console.

RELATED TAGS

typescript
locale string
array
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring