0
0
JavascriptHow-ToBeginner · 3 min read

How to Join Array into String in JavaScript: Simple Guide

In JavaScript, you can join an array into a string using the join() method. This method combines all array elements into one string, separated by a specified delimiter or a comma by default.
📐

Syntax

The join() method syntax is:

  • array.join(separator)

Where:

  • array is the array you want to join.
  • separator is an optional string to separate each element in the resulting string. If omitted, a comma , is used by default.
javascript
array.join(separator)
💻

Example

This example shows how to join an array of words into a sentence separated by spaces.

javascript
const words = ['Hello', 'world', 'from', 'JavaScript'];
const sentence = words.join(' ');
console.log(sentence);
Output
Hello world from JavaScript
⚠️

Common Pitfalls

One common mistake is forgetting to provide a separator, which results in commas between elements by default. Another is joining arrays with non-string elements without converting them, which can cause unexpected results.

javascript
const numbers = [1, 2, 3];
// No separator provided, default comma used
console.log(numbers.join()); // Output: "1,2,3"

// Specify separator
console.log(numbers.join('-')); // Output: "1-2-3"
Output
1,2,3 1-2-3
📊

Quick Reference

Remember these tips when using join():

  • Default separator is a comma ,.
  • Use '' (empty string) to join without any separator.
  • Works on all array elements, converting them to strings.

Key Takeaways

Use join() to combine array elements into a string with a separator.
If no separator is given, elements are joined with commas by default.
Specify an empty string '' to join elements without spaces or commas.
All array elements are converted to strings before joining.
Always choose a separator that fits your desired output format.