Rest and spread both use three dots, so they can be confusing. Let’s take the time to understand these helpful JavaScript operators.
The rest and spread operators are two of the advanced features introduced in ES6, allowing us to spread out and mix several elements. These two operators haven’t received as much attention in recent development, yet they play a significant role in writing clean and efficient code. For example, they offer a compelling alternative to the concat method, which was introduced back in ES3.
These two operators often need clarification because they appear to be similar since they are both designated by three periods, yet they perform separate functions.
In this post, we will discuss the rest and spread operators in JavaScript, their differences, when to use them and how to apply them sequentially in our projects to create effective code.
As stated from the beginning, the rest and spread operators are two different operators, but they have a common symbol: the three dots in JavaScript. Woah! Still trying to understand, right? Why are they both using three dots in JavaScript if they are not the same? Well, this is where it gets tricky, but I will explain it as we proceed.
A rest operator is a type of parameter that gets all of the remaining parameters of a function call via an Array. It enables us to handle a variety of inputs as parameters in a function. Because it is used to combine many items, the rest operator is very helpful during array and object destructuring.
Let’s see an example of a rest operator. Here we’ll add the sum of numbers using a rest operator, which is the ...
:
function sum(...numbers) {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
const result =console.log (sum(1, 2, 3, 4));
// This returns 10 (1 + 2 + 3 + 4)
In the code example above, we created a function sum
. Inside the parentheses, we added the rest parameter that will allow the function to accept any number of arguments and gather them into an array called numbers. Next, we created a variable total
and assigned an initial value of 0 to this variable, which will eventually store the sum of all the numbers.
The loop will iterate through each element in the numbers array then the const num will declare a variable num that represents the current number that’s being processed in the loop. Inside the loop, the next line, total+=num
adds the current number num
to the total sum
. Once the loops finishes, the function will return the total, which is the sum of all the numbers.
The final line invokes the function, which takes four inputs. All arguments are gathered into the numbers array within the function. These numbers are then added together using the loop, and the result, which is 10, is saved in the result
variable.
This code sample summarizes our definition of rest: The rest operator combines elements or arguments of a function into an array.
The spread operator divides an array or object into separate elements or properties. The spread operator is mostly used if you want to duplicate the content of an array or combine or combine multiple arrays/objects together.
For instance, if we have an array of numbers and want to build a new array with the elements of the first array we made by adding another element to the end of the first array we formed, we will use the spread operator (again, it’s ...
) since what we want to do here is combine two arrays.
const firstArray = [5, 10, 15, 20, 25, 30];
const newArray=[...firstArray, 35, 40]
If you study the code carefully, you will notice we did a little concatenation using the spread operator.
Great! So, we have come a long way by learning what the two operators are. The next step is how to apply them. Well, this shouldn’t freak you out, as we will break down how we can use them in our code. To understand this better, we are going to use real-life examples, but we will use code for a better understanding
Let’s look at a simple example of spread. For example, when you are preparing a fruit salad, you have different bowls that contain different fruits, and you want to combine them into one big bowl to mix the fruit. Here is an example of how the spread operator works in the context of this example:
const firstBowl = ['pawpaw', 'cucumber', 'watermelon'];
const secondBowl = ['Pineapple', 'Apple', 'banana'];
const thirdBowl = ['cashew nut', 'Date', 'Strawberry'];
const fruitMix = [...firstBowl, ...secondBowl, ...thirdBowl];
console.log(fruitMix);
In the above example, the spread operator is used to split the content of each fruit bowl into the fruitMix
array, which will combine all the fruits from the different bowls to make a fruit salad.
The spread operator can be used to combine items from different sources into one collection.
Rest is quite simple as we will calculate the total age of guests attending a party we are hosting. You know some guests will bring their children along as well, so we will need a way to handle different numbers of ages. To do that, we will create a function calculateTotalAge
. This function will sum up the age of both the host and guests. See the code example below:
function calculateTotalAgeOfGuest(hostAge, ...guestAges) {
let totalAge = hostAge;
for (const age of guestAges) {
totalAge += age;
}
return totalAge;
}
const hostAge = 30;
const guestAges = [25, 28, 10, 5];
const totalAge = calculateTotalAgeOfGuest(hostAge, ...guestAges);
From the code example above, the rest operator collects all the guests’ ages into the array guestAges
. This makes it much easier to calculate the total age by looping through the array.
The rest operator collects multiple amounts of something into a single container for processing, such as the age calculation we performed.
Deciding when to utilize the rest or spread operator hinges solely on your personal preference and type of project you’re working on.
For instance, the spread operator can be used in function calls, array literals and object literals. Iterables such as arrays and strings can be stretched into just one argument or element with the spread operator. Object expressions will be expanded to create a new object. While the rest operator gathers all remaining elements or arguments into an array.
In summary, this means that the rest operator is used to gather elements into an array, while the spread operator is used to spread the content of an array.
Rest and spread operators might initially seem perplexing, but integrating them into your programming tasks makes them easier to understand. In this article, we have delved into the fundamental concepts behind rest and spread operators and provided practical insights into their application. By now, you should have gained a clear understanding of these two operators, and we hope that this article proves to be a valuable resource in enhancing your comprehension of their usage.
Ezekiel Lawson is a technical writer and software developer. Aside from building web tools and applications, he enjoys educating people and simplifying complicated issues for their easy understanding by sharing resources that will guide developers through technical writing.