javascript
  1. javascript-join

JavaScript join()

The join() method in JavaScript is used to join all the elements of an array into a string. It takes an optional separator parameter, which is inserted between each element in the resulting string.

Syntax

array.join(separator)
  • array: The array whose elements are to be joined into a string.
  • separator: Optional. The separator to be used between each element in the resulting string. If omitted, the elements are joined into a string with no separator.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array Join Example</title>
</head>
<body>

<!-- Placeholder for displaying the output -->
<p id="output"></p>

<script>
    // Array
    const fruits = ["apple", "banana", "orange"];

    // Join array elements into a string
    const fruitString = fruits.join(", ");

    // Display the joined string
    document.getElementById("output").innerHTML += "Joined String: " + fruitString;
</script>

</body>
</html>
Try Playground

In this example, the join() method is called on the fruits array with a separator of ", ". The resulting string is then stored in the fruitString variable, which is logged to the console.

Output

The join() method returns a string that consists of all the elements of the array joined together with the specified separator.

Explanation

The join() method takes all the elements of an array and concatenates them into a single string, separated by the specified separator. If no separator is provided, the elements are joined into a string with no separator.

Use

The join() method can be used whenever you need to convert the elements of an array into a single string, separated by a given separator. It is often used when working with user input, form data, or any other data that needs to be represented as a string.

Important Points

  • The join() method does not modify the original array.
  • When using join() with an empty separator (array.join("")), all the elements of the array are joined together with no separator between them.
  • If any element in the array is null or undefined, it is converted to an empty string in the resulting string.

Summary

The join() method in JavaScript is a useful tool for joining the elements of an array into a single string. It takes an optional separator parameter and returns a string that consists of all the elements of the array joined together with the specified separator. This method is frequently used to convert user input or form data into a string.

Published on: