Skip to main content

Spread Operator

How to Use the Spread Operator (…) in JavaScript

The spread operator is a powerful JavaScript feature introduced in ECMAScript 6 (ES6) and denoted by three dots (...). It expands the values of an iterable (such as an array, string, or object) to enable you to access and manipulate the iterable.

Whether you're a beginner or an experienced JavaScript developer, learning how to use the spread operator is an essential skill that will take your coding to the next level. In this article, we'll explore the ins and outs of the spread operator and show you how to use it to write cleaner, more efficient code. So, let's get started!


Using the Spread Operator in Arrays

The spread operator is commonly used in JavaScript to expand the elements of an array. In this section, you'll learn how to concatenate and copy arrays using the spread operator.

const arrValue = ["Hello", "JavaScript"];

console.log(arrValue); //👉 Output: [ 'Hello', 'JavaScript' ]
console.log(...arrValue); //👉 Output: Hello JavaScript

👉 Concatenation

Concatenation is the process of joining two or more arrays to create a new large array. In JavaScript, you can concatenate arrays using the spread operator (...).

To concatenate two arrays using the spread operator, simply spread the arrays inside a new array, like this:

const vowels = ["a", "e", "i", "o", "u"];
const random = ["b", "d", "f"];

const merged = [...vowels, ...random];
console.log(merged); //👉🏻 Output: ['a', 'e', 'i', 'o', 'u', 'b', 'd', 'f']

From the code snippet above, there are two arrays - vowels and random. They are merged into one, called merged - containing all the elements of the arrays.


👉 Copying an Array

The spread operator provides a convenient way to copy an array into another array. It is useful when you want to manipulate an array without affecting the original array.

To copy an array using the spread operator, spread the original array inside square brackets []; like this:

const vowels = ["a", "e", "i", "o", "u"];
const backup = [...vowels];

console.log(backup); //👉🏻 Output: [ 'a', 'e', 'i', 'o', 'u' ]

From the code snippet above, the backup array copies all the elements in the vowels array.

💡 Any further changes to the vowels array will not reflect in the backup array, unlike the regular assignment operator.

const vowels = ["a", "e", "i", "o", "u"];
const backup = [...vowels];
const newArray = vowels;
vowels.pop(); //👉🏻 removes the last element from the array

console.log(vowels); //👉🏻 [ 'a', 'e', 'i', 'o' ]
console.log(backup); //👉🏻 [ 'a', 'e', 'i', 'o', 'u' ]
console.log(newArray); //👉🏻 [ 'a', 'e', 'i', 'o' ]

The newArray variable creates a reference to the vowels variable instead of copying the entire array value.


Using the Spread Operator in Functions

The spread operator can be used to accept an array of parameters in JavaScript functions; in this case, it is called the Rest Operator. It captures any number of arguments passed to the function and groups them into an array.

💡 When you place the spread operator before the parameter name of a function declaration, it is called the Rest Operator.

function sumNumbers(...args) {
let sum = 0;
for (const num of args) {
sum += num;
}
console.log(sum);
}

sumNumbers(1, 2, 3, 4, 5, 6, 7, 8, 9); // 👉🏻 Output: 45

In the example above, the function sumNumbers accepts an array of numbers with an undefined length using the rest operator, then loops through the arguments to add each number together and log the result to the console.


Using the Spread Operator in Objects

The spread operator isn't just limited to arrays in JavaScript; it can be used with objects to execute tasks such as copying, merging, and updating object properties.


👉 Copying Object Properties

With the spread operator, you can copy the properties of an object into a new object. This is useful when creating a copy of an object without modifying the original object.

To copy an object using the spread operator, spread the original object inside a new object. Take a look at this example:

const book = {
name: "Rich Dad Poor Dad",
author: "Robert Kiyosaki",
};
const bookInfo = {
...book,
pages: 336,
year: 1997,
};

console.log(bookInfo);
/* 👇🏻 Output: {
name: 'Rich Dad Poor Dad',
author: 'Robert Kiyosaki',
pages: 336,
year: 1997
} */

In the example above, the bookInfo object copies the properties of the book object by using the spread operator to copy the properties of the original book object into the bookInfo object.


👉 Merging Objects Properties

You can merge two or more objects into a single object using the spread operator (...). The spread operator provides a simple way to combine the properties of multiple objects into a single object without modifying the original objects.

To merge objects using the spread operator, spread each object inside curly braces {}. Consider the example below:

const info1 = {
name: "Rich Dad Poor Dad",
author: "Robert Kiyosaki",
};
const info2 = {
pages: 336,
year: 1997,
};

const bookInfo = { ...info1, ...info2 };
console.log(bookInfo);
/* 👇🏻 Output: {
name: 'Rich Dad Poor Dad',
author: 'Robert Kiyosaki',
pages: 336,
year: 1997
} */

In the example above, the two objects - info1 and info2 are merged into one using the spread operator.


👉 Updating Object Properties

You can also update the properties of an object with the JavaScript spread operator.

To update an object's properties using the spread operator, you can spread the original object inside a new object, and specify the new values for the properties you want to update, like this:

const book = {
name: "Rich Dad Poor Dad",
author: "Robert Kiyosaki",
year: 2000,
};

const bookInfo = {
...book,
year: 1997,
};
console.log(bookInfo);
/*👉🏻 Output: { name: 'Rich Dad Poor Dad', author: 'Robert Kiyosaki', year: 1997 } */

The code snippet above updates the year property within the bookInfo object. In some cases, if you need the previous year property, you can create a nested object within the bookInfo object as shown below:

const book = {
name: "Rich Dad Poor Dad",
author: "Robert Kiyosaki",
year: 2000,
};
const bookInfo = {
...book,
year: 1997,
previous: { ...book },
};
console.log(bookInfo);
/* 👇🏻 Output: {
{
name: 'Rich Dad Poor Dad',
author: 'Robert Kiyosaki',
year: 1997,
previous: { name: 'Rich Dad Poor Dad', author: 'Robert Kiyosaki', year: 2000 }
}
*/

✅ Key Takeaways

  • The JavaScript spread operator is denoted by three dots (...) and can be used to manipulate arrays and objects.
  • With the spread operator, you can create new arrays by adding elements and combining multiple arrays.
  • With the spread operator, you can create new objects by adding or updating object properties and merging multiple objects into one.
  • You can pass multiple arguments into a JavaScript function using the rest operator.
  • The spread operator simplifies and makes your code more readable and efficient.

✅ Resources