Codectionary / Developer documentation / JavaScript

concat() and join()

concat() merges two or more arrays into a new array, without modifying the originals. join() converts all array elements into a single string, separated by a specified delimiter (comma by default) - the reverse operation of String.prototype.split().

Syntax

arr.concat(otherArr)
arr.join(separator)

Examples

concat() - Merging Arrays

Combining arrays without mutating the originals.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4, 5, 6]
console.log(arr1);   // [1, 2, 3] - unchanged

// concat() can also merge multiple arrays and add individual values
const combined = arr1.concat(arr2, [7, 8], 9);
console.log(combined); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

join() - Array to String

Converting array elements into a formatted string.

const words = ["Hello", "World", "!"];

console.log(words.join(" ")); // "Hello World !"
console.log(words.join());    // "Hello,World,!" - default separator is a comma
console.log(words.join(""));  // "HelloWorld!" - no separator

const path = ["usr", "local", "bin"];
console.log(path.join("/")); // "usr/local/bin"

Best practices

  • Prefer the spread operator ([...arr1, ...arr2]) over concat() in modern code - it reads more clearly, though both achieve the same result
  • Use join() instead of manually looping and building a string when converting an array to display text
  • Choose a join() separator that matches your output format - commas for CSV-like data, spaces for sentences, "/" for paths
  • Remember join() converts non-string elements using their default string representation, which may need formatting first for numbers or objects

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation