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 TypeScriptlet 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 stringconsole.log(names.join(" ")) // separated by spaceconsole.log(numbers.join("+")) // separated by "+"console.log(cars.join("/")) // separated by "/"
Explanation
- Lines 2–5: We declare three arrays:
names,numbers, andcarsand initialize them with elements.
- Line 8: We use the
join()method to combine the elements ofnamesusing the separator," ", and print the returned string to the console.
- Line 9: We use the
join()method to combine the elements ofnumbersusing the separator,"+", and print the returned string to the console.
- Line 10: We use the
join()method to combine the elements ofcarsusing the separator,"/", and print the returned string to the console.