How to use the JavaScript spread operator effectively

Gilles FerrandGilles Ferrand
4 min read

The spread operator (...) is one of the most useful features in modern JavaScript. It allows you to expand arrays, objects, and other iterable elements in places where multiple elements are expected. This article will explain how to use the spread operator effectively.

What is the spread operator

The spread operator uses three dots (...) before a variable name. It "spreads" or expands the contents of arrays, objects, or strings into individual elements.

console.log([🍏,🍐,🍊]); // Output: [🍏,🍐,🍊]
// With spread operator
console.log(...[🍏,🍐,🍊]); // Output: 🍏 🍐 🍊

Using spread operator with Arrays

You can create a shallow copy of an array

const originalArray = [🍏,🍐,🍊];
const copiedArray = [...originalArray];

console.log(copiedArray); // [🍏,🍐,🍊]

You can merge multiple arrays easily

const fruits = [🍏, 🍌];
const vegetables = [πŸ₯•, 🍠];
const food = [...fruits, ...vegetables];

console.log(food); // [🍏, 🍌, πŸ₯•, 🍠]

You can insert new elements while keeping existing ones

const healthyFood = [🍏, 🍌, πŸ₯•, 🍠];
const moreHealthyFood = [πŸ‘, ...healthyFood, πŸ₯¦, πŸ₯‘];

console.log(moreHealthyFood); // [πŸ‘, 🍏, 🍌, πŸ₯•, 🍠, πŸ₯¦, πŸ₯‘]

Using spread operator with Object

You can create a shallow copy of an object

const person = { name: 'Gilles', age: 29 };
const personCopy = { ...person };

console.log(personCopy); // { name: 'Gilles', age: 29 }

You can combine multiple objects into one

const person = { name: 'Gilles', age: 29 };
const contactInfo = { email: 'gilles@email.com', phone: '123-456-7890' };
const fullProfile = { ...person, ...contactInfo };

console.log(fullProfile);
// { name: 'Gilles', age: 29, email: 'gilles@email.com', phone: '123-456-7890' }

You can override specific properties of an object while keeping others

const person = { name: 'Gilles', age: 29, city: 'Toulouse' };
const updatedPerson = { ...person, age: 29, country: 'France' };

console.log(updatedPerson);
// { name: 'Gilles', age: 29, city: 'Toulouse', country: 'France' }

Using Spread with Function Arguments

You can pass array elements as separate arguments to functions:

function addThreeNumbers(a, b, c) {
    return a + b + c;
}

const numbers = [5, 10, 15];
const result = addThreeNumbers(...numbers);

console.log(result); // 30

Using Spread with Strings

You can spread a string into individual characters:

const word = 'hello';
const letters = [...word];

console.log(letters); // ['h', 'e', 'l', 'l', 'o']

Important Notes

Shallow Copy Limitation

The spread operator creates shallow copies, not deep copies. This means nested objects or arrays are still referenced:

const original = { 
    name: 'Gilles', 
    hobbies: ['reading', 'coding'] 
};

const copy = { ...original };
copy.hobbies.push('cycling');

console.log(original.hobbies); // ['reading', 'coding', 'cycling']
// The original object is affected!

Order Matters

When merging objects, properties from later objects override earlier ones:

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 }
// obj2.b overrides obj1.b

Deep Copying with Spread

While the spread operator creates shallow copies, you can achieve deep copying by combining it with other techniques:

// For simple nested objects (no functions, dates, etc.)
const original = {
    name: 'Gilles',
    address: { city: 'Toulouse', country: 'France' },
    hobbies: ['reading', 'coding']
};

const deepCopy = {
    ...original,
    address: { ...original.address },
    hobbies: [...original.hobbies]
};

// Now changes to deepCopy won't affect original
deepCopy.address.city = 'MontrΓ©al';
deepCopy.hobbies.push('cycling');

console.log(original.address.city); // 'Toulouse' (unchanged)
console.log(original.hobbies); // ['reading', 'coding'] (unchanged)

Real life example in React and Angular

React Use Cases

The spread operator is essential in React for:

  • State updates: Change one property in a state object while keeping others unchanged

  • Props passing: Send multiple properties to child components at once

  • Array state management: Add or remove items from lists without mutating the original array

  • Event handling: Create new objects when updating form data

  • Component composition: Combine default props with custom props

Angular Use Cases

In Angular, the spread operator helps with:

  • Data binding: Update component properties while preserving existing data

  • Array manipulation: Add, remove, or modify items in lists for templates

  • Form handling: Create updated objects when processing form submissions

  • API responses: Merge server data with local component state

  • Template data: Combine multiple data sources for display

Both frameworks benefit from the spread operator because it helps create new objects and arrays instead of modifying existing ones, which prevents unexpected bugs and makes applications more predictable.

Conclusion

The spread operator is a powerful tool that makes JavaScript code cleaner and more readable. It simplifies many common tasks like copying arrays, merging objects, and passing arguments to functions. With careful use, you can even achieve deep copying without external libraries.

Practice using the spread operator in your projects to become more comfortable with this essential JavaScript feature. Start with simple cases and gradually work your way up to more complex scenarios.

0
Subscribe to my newsletter

Read articles from Gilles Ferrand directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gilles Ferrand
Gilles Ferrand

Full stack engineer but passionnated by front-end Angular Expert / NX / JavaScript / Node / Redux State management / Rxjs