Skip to content
DeveloperMemos

How to Use the Spread Operator in JavaScript

JavaScript, ES6, ES20151 min read

In JavaScript, the spread operator (...) is a powerful feature introduced in ES6 (ES2015) that allows you to expand elements from an iterable (like an array or string) into individual elements. It provides a concise syntax for manipulating arrays and objects, making your code more expressive and efficient.

Using the Spread Operator with Arrays

Combining arrays

One of the most common use cases of the spread operator is to combine multiple arrays into a single array. Let's say we have two arrays, arr1 and arr2, and we want to create a new array that contains all the elements from both arrays. We can achieve this easily using the spread operator:

1const arr1 = [1, 2, 3];
2const arr2 = [4, 5, 6];
3
4const combinedArray = [...arr1, ...arr2];
5console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]

Copying an array

The spread operator can also be used to create a copy of an existing array. This is useful when you want to modify an array without affecting the original one. Here's how you can make a copy using the spread operator:

1const originalArray = [1, 2, 3];
2const copiedArray = [...originalArray];
3
4console.log(copiedArray); // Output: [1, 2, 3]
5console.log(originalArray === copiedArray); // Output: false

Adding elements to an array

You can use the spread operator to add new elements to an existing array. Let's say we have an array numbers and we want to add a new number at the end. Here's how you can do it:

1const numbers = [1, 2, 3];
2const newArray = [...numbers, 4];
3
4console.log(newArray); // Output: [1, 2, 3, 4]

Using the Spread Operator with Objects

Copying an object

Similar to copying arrays, the spread operator can be used to create a copy of an object. When spreading an object, it creates a shallow copy, meaning that nested objects are still referenced. Here's an example:

1const originalObject = { name: "John", age: 30 };
2const copiedObject = { ...originalObject };
3
4console.log(copiedObject); // Output: { name: "John", age: 30 }
5console.log(originalObject === copiedObject); // Output: false

Merging objects

The spread operator is also handy for merging objects together. Suppose we have two objects, obj1 and obj2, and we want to combine their properties into a single object. We can achieve this using the spread operator:

1const obj1 = { name: "John" };
2const obj2 = { age: 30 };
3
4const mergedObject = { ...obj1, ...obj2 };
5console.log(mergedObject); // Output: { name: "John", age: 30 }

Modifying object properties

You can use the spread operator to modify specific properties of an object while keeping the rest unchanged. Here's an example of updating the age property of an object:

1const person = { name: "John", age: 30 };
2const updatedPerson = { ...person, age: 31 };
3
4console.log(updatedPerson); // Output: { name: "John", age: 31 }