The JavaScript Spread Operator, denoted by three dots (...), allows an iterable (like an array or string) to be expanded or “spread” into places where zero or more arguments or elements are expected.

Think of it as taking a box of items and unpacking them all at once onto a table, rather than taking them out one by one.

Here is a breakdown of how to use it effectively with Arrays, Objects, and Functions.

1. Basic Syntax

const arr = [1, 2, 3];
console.log(...arr); // 1 2 3
  • …arr “spreads” the array elements
  • Works with arrays, strings, objects, maps, sets, and iterables

2. Spread in Function Calls

function sum(a, b, c) {
return a + b + c;
}const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
  • Without spread:
sum(numbers); // NaN
  • Spread expands array elements into individual arguments

3. Combining Arrays

Before ES6:

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

Using spread:

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // [1,2,3,4]
  • Very useful for merging arrays
  • Can insert elements in between:
const arr = [0, ...arr1, 5, ...arr2, 6];
console.log(arr); // [0,1,2,5,3,4,6]

4. Copying Arrays

Spread operator creates a shallow copy:

const original = [1, 2, 3];
const copy = [...original];copy.push(4);
console.log(original); // [1,2,3]
console.log(copy); // [1,2,3,4]
  • Avoids direct reference assignment (let copy = original;) which modifies the same array.

5. Spread with Strings

Strings are iterable:

const str = "Hello";
const chars = [...str];
console.log(chars); // ["H","e","l","l","o"]console.log(...str); // H e l l o
  • Useful for splitting strings into arrays of characters

6. Spread with Objects (ES2018+)

You can merge or copy objects:

const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };const merged = { ...obj1, ...obj2 };
console.log(merged); // { a:1, b:3, c:4 }
  • Later properties overwrite earlier ones (b was 2, now 3)
  • Shallow copy only (nested objects still reference original)

7. Adding / Updating Properties

const user = { name: "Zaman", age: 25 };
const updatedUser = { ...user, age: 26, country: "BD" };
console.log(updatedUser); // {name:"Zaman", age:26, country:"BD"}

8. Spread in Destructuring

const arr = [1,2,3,4,5];
const [first, second, ...rest] = arr;console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3,4,5]
  • This uses rest operator, which is conceptually opposite to spread, but same … syntax.

Categorized in:

Javascript ES6,