Open In App

TypeScript Array join() Method

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Array.join() method in TypeScript is a built-in function used to join all the elements of an array into a single string. This method is particularly useful when you need to concatenate array elements with a specific separator.

Syntax

Here, we will see the syntax of the join() method and understand its parameters.

array.join(separator?: string): string;

Parameter

This method accept a single parameter as mentioned above and described below:

  • separator (Optional): A string used to separate each element of the array in the resulting string. If omitted, the array elements are separated by commas.

Return Value

  • This method returns a single string containing all the array elements joined by the specified separator.

Examples of TypeScript Array join() Method

Example 1: Joining Numbers with Default Separator

In this example, we join an array of numbers into a single string using the default comma separator.

TypeScript
let numbers: number[] = [11, 89, 23, 7, 98];
let result: string = numbers.join();
console.log("String:", result);

Output: 

String: 11,89,23,7,98

Example 2: Joining Strings with Custom Separators

This example demonstrates how to join an array of strings using different separators.

TypeScript
let letters: string[] = ["a", "b", "c", "a", "e"];

// Using a space as a separator
let resultSpace: string = letters.join(' ');
console.log(resultSpace);
// Using a plus sign as a separator
let resultPlus: string = letters.join(' + ');
console.log(resultPlus);

Output: 

a b c a e
a + b + c + a + e

Next Article

Similar Reads