TypeScript Array join()
Syntax & Examples


Array.join() method

The join() method joins all elements of an array into a string and returns this string. Elements are separated by the specified separator string. If no separator is provided, the elements are separated by a comma.


Syntax of Array.join()

The syntax of Array.join() method is:

join(separator?: string): string

This join() method of Array adds all the elements of an array separated by the specified separator string.

Parameters

ParameterOptional/RequiredDescription
separatoroptionalA string used to separate each of the elements in the resulting string. If omitted, the array elements are separated with a comma.

Return Type

Array.join() returns value of type string.



✐ Examples

1 Using join() with default separator

The join() method can be used to join all elements of an array into a string with elements separated by a comma.

For example,

  1. Create an array arr with string values ['apple', 'banana', 'cherry'].
  2. Use join() without any arguments to join the elements into a string.
  3. Store the result in result.
  4. Log result to the console.

TypeScript Program

const arr = ['apple', 'banana', 'cherry'];
const result = arr.join();
console.log(result);

Output

'apple,banana,cherry'

2 Using join() with a specified separator

The join() method can be used to join all elements of an array into a string with elements separated by a specified separator.

For example,

  1. Create an array arr with numeric values [1, 2, 3, 4, 5].
  2. Use join('-') to join the elements into a string separated by hyphens.
  3. Store the result in result.
  4. Log result to the console.

TypeScript Program

const arr = [1, 2, 3, 4, 5];
const result = arr.join('-');
console.log(result);

Output

'1-2-3-4-5'

3 Using join() with an empty separator

The join() method can be used to join all elements of an array into a string with no separator between elements.

For example,

  1. Create an array arr with string values ['a', 'b', 'c', 'd'].
  2. Use join('') to join the elements into a string with no separator.
  3. Store the result in result.
  4. Log result to the console.

TypeScript Program

const arr = ['a', 'b', 'c', 'd'];
const result = arr.join('');
console.log(result);

Output

'abcd'

Summary

In this TypeScript tutorial, we learned about join() method of Array: the syntax and few working examples with output and detailed explanation for each example.