- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Array concat and join
JavaScript Arrays
JavaScript Array concat and join
JavaScript
concatjoins two arrays together andjointurns an array into a string.
Both return something new and leave the original arrays alone.
join is the usual way to display a list on a page.
Example
Example
javascript
const a = [1, 2];
const b = [3, 4];
console.log(a.concat(b).join("-"));The output is 1-2-3-4.
concat and join
concat returns a new array containing the elements of both.
join returns a string with every element separated by the text you choose.
Neither method changes the arrays they are called on.
Syntax
Syntax
javascript
array1.concat(array2);
array.join(separator);The default separator for join is a comma.
Joining Several Arrays
concat accepts more than one array.
Example
Example
javascript
const a = [1];
const b = [2];
const c = [3];
console.log(a.concat(b, c).join(","));The output is 1,2,3.
The Spread Alternative
Modern code often uses spread instead, which reads a little more directly.
Example
Example
javascript
const a = [1, 2];
const b = [3, 4];
console.log([...a, ...b].join(","));The result is the same as concat.
Choosing a Separator
Any string can be the separator, including an empty one.
Example
Example
javascript
const letters = ["a", "b", "c"];
console.log(letters.join(""));
console.log(letters.join(" and "));An empty separator glues the elements together with nothing between them.
join Handles null and undefined
Empty values become empty strings rather than the words null or undefined.
Example
Example
javascript
const list = ["a", null, "c"];
console.log(list.join("-"));The output is a--c, with nothing where the null was.
toString is Similar
toString() is the same as join(",") with no choice of separator.
Example
Example
javascript
const list = [1, 2, 3];
console.log(list.toString());Use join when you want to control the separator.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript concat and join</title>
</head>
<body>
<h1>JavaScript concat and join</h1>
<p id="result"></p>
<script>
const first = ["Ada", "Grace"];
const second = ["Alan"];
const all = first.concat(second);
document.getElementById("result").innerHTML = all.join(" · ");
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try a different separator:
Change the join to join(", ") and compare the output.
Important Points
concatreturns a new array holding both lists.- Spread is a common modern alternative to
concat. jointurns an array into a string.- The default separator is a comma.
nullandundefinedbecome empty strings in the result.
Conclusion
concat combines arrays and join turns one into text.
Both leave the original arrays untouched.
join is how most lists end up on the page.
