What is the join() method of an array in TypeScript?

Overview

The join() method in TypeScript is used to join the elements of an array as a string.

Syntax

array.join(separator)
Syntax for join() method of an array in TypeScript

Parameter

separator: This is a character or string that separates each element of the array when joined as a string.

Return value

This method returns the combination of all the elements of the array as a single string.

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"]
// print elements of the arrays as a string
console.log(names.join(" ")) // separated by space
console.log(numbers.join("+")) // separated by "+"
console.log(cars.join("/")) // separated by "/"

Explanation

  • Lines 2–5: We declare three arrays: names, numbers, and cars and initialize them with elements.
  • Line 8: We use the join() method to combine the elements of names using the separator, " ", and print the returned string to the console.
  • Line 9: We use the join() method to combine the elements of numbers using the separator, "+", and print the returned string to the console.
  • Line 10: We use the join() method to combine the elements of cars using the separator, "/", and print the returned string to the console.

Free Resources