Mastering the concat() Method in JavaScript

Introduction

The concat() method in JavaScript is used to **merge two or more arrays or strings**. It does **not modify the original arrays or strings** but returns a new array or string containing all combined elements. 🔗

📌 What is concat()?

concat() is a simple and safe way to join arrays or strings together. It's immutable, meaning it will **never change** the source array or string — instead, it produces a new one.

  • ✔️ Merges arrays or strings
  • 🔄 Returns a new array or string
  • ⚡ Does not alter the original arrays/strings

💡 Syntax

Basic Syntax

array1.concat(array2, array3, ..., arrayN)
string1.concat(string2, string3, ..., stringN)

🧵 Example: Concatenating Arrays

Array concatenation

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2);

console.log(combined); // [1, 2, 3, 4]
console.log(arr1); // [1, 2] (original unchanged)

🍏 Example: Concatenating Multiple Arrays

Multiple arrays combined

const arrA = [1];
const arrB = [2, 3];
const arrC = [4, 5];
const merged = arrA.concat(arrB, arrC);

console.log(merged); // [1, 2, 3, 4, 5]

📝 Example: Concatenating Strings

String concatenation

const str1 = "Hello";
const str2 = " World";
const greeting = str1.concat(str2);

console.log(greeting); // "Hello World"
console.log(str1); // "Hello" (original unchanged)

⚠️ Important Notes

Note

  • concat() is **non-destructive**; original arrays/strings remain unchanged.
  • It can combine arrays with arrays or values with arrays.
  • For arrays, consider using the **spread operator** [...arr1, ...arr2] as a modern alternative.

📊 Quick Reference Table

CodeOutput
[1, 2].concat([3, 4])[1, 2, 3, 4]
"Hello".concat(" ", "World")"Hello World"
[1].concat([2], [3, 4])[1, 2, 3, 4]
>>"concat() is the glue that binds arrays and strings together — safely and immutably." 🔗

🔥 Summary

The concat() method is perfect for merging arrays or strings without modifying the originals. Use it when you need a new combined array or string and want to keep the original data intact.