JavaScript  

The Spread Operator in JavaScript

Introduction

The spread operator (...) lets you unpack elements from arrays or objects. It's often used to copy, merge, or expand data.

Syntax

const arr = [1, 2, 3];
const newArr = [...arr];
console.log(newArr); // [1, 2, 3]

The ... in front of arr tells JavaScript.

Take all the elements inside arr and add them to newArr

Spread in Arrays
 

1. Cloning an Array

const original = [10, 20, 30];
const clone = [...original];

console.log(clone); // [10, 20, 30]

Note. This creates a shallow copy, meaning it copies the top-level elements.

2. Merging Arrays

const nums1 = [1, 2];
const nums2 = [3, 4];
const combined = [...nums1, ...nums2];

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

So now you don't need to use .concat() anymore.

3. Add Elements While Merging

const list = [2, 3];
const newList = [1, ...list, 4];

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

Spread in Objects
 

1. Copy an Object

const user = { name: "Sam", age: 30 };
const userCopy = { ...user };

console.log(userCopy); // { name: "Sam", age: 30 }

Useful when you want to keep the original object untouched.

2. Merge Objects

const info = { name: "Alex" };
const details = { age: 25 };
const fullProfile = { ...info, ...details };

console.log(fullProfile); // { name: "Alex", age: 25 }

Spread in Function Arguments

Instead of passing items one by one, use spread to unpack an array into arguments.

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6

Things to Watch Out For

Spread makes a shallow copy: it won’t deeply clone nested data.

const original = {
  name: "Alice",
  details: {
    age: 30,
    city: "Paris"
  }
};

// Shallow copy using spread
const copy = { ...original };

// Modify nested object
copy.details.city = "London";

console.log(original.details.city); // London
console.log(copy.details.city);     // London

Even though we copied the original using spread ({ ...original }), the details object inside it was not cloned, both original.details and copy.details still point to the same inner object in memory.

That’s what we mean by shallow copy: it only copies the top level, not nested objects or arrays.

Conclusion

When to use the spread operator?

  • Copy arrays or objects
  • Combine or extend them
  • Pass array elements as function arguments