DEV Community

Cover image for How to use Spread and Rest operators in JavaScript
Hyemiie
Hyemiie

Posted on

How to use Spread and Rest operators in JavaScript

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Understanding Spread Operators
  4. Rest Operators
  5. How to identify rest and spread operators

Introduction

Spread and Rest operators are features of ES6 JavaScript that make it easier to access and manipulate elements in an array. Although they both have a similar syntax represented by the three dots (...), they have different functionalities and use cases.

In this article, we would look at the core usages of these operators and explore practical examples that highlight their applications in real-world scenarios. By the end, you will have a comprehensive understanding of how to use these operators effectively in your JavaScript code.

Prerequisites
To follow up with this article, you need to be familiar with some basic JavaScript concepts including

  • Variables and data types
  • Arrays and array manipulation
  • Objects and object properties
  • Functions and function parameters.

Spread Operators
A Spread operator is a feature that is used to access elements of iterable, such as arrays and objects, as individual elements.
Let's consider an example where we have a student named John who submitted his exam scores.

var JohnScores = [75, 88, 69, 57, 92];

Enter fullscreen mode Exit fullscreen mode

To create a profile for John based on these scores, we would need to access each score and save it in his profile. Now, this is where spread operators come in handy…

var JohnScores = [75, 88, 69, 57, 92];


var John = {
  Name: 'John',
  Class: 'Grade1',
  Age: 19,
  Scores: [...JohnScores],
};


console.log(John)

Enter fullscreen mode Exit fullscreen mode

By using the spread operator [...JohnScores], we include the elements of the array JohnScores as separate elements within the Scores property of the John object as shown in the console.


Object
Age: 19
Class: "Grade1"
Name: "John"
Scores: (5) [75, 88, 69, 57, 92]
[[Prototype]]: Object.

Enter fullscreen mode Exit fullscreen mode

How to use Spread operators

1. Passing elements of an array as parameters

For example, let’s create a function that calculates the average of John’s scores.

var JohnScores = [75, 88, 69, 57, 92];

function average(Score1 , Score2 , Score3 , Score4 ,Score5){
 sum = Score1 + Score2 + Score3 + Score4 + Score5;
 avg = sum/5;
console.log(avg)
}

average(...JohnScores)


// OUTPUT WOULD BE 76.4

Enter fullscreen mode Exit fullscreen mode

In the code snippet, we created a function that accepts five parameters and calculates the average of the parameters.
To calculate the average of John's scores, we invoke the average function and pass the individual scores using the Spread operator ...JohnScores. This will expand the array of elements and pass them as separate arguments to the average function.

In cases where the values in the array are more than the parameters mentioned in the function, the spread operator is only going to take the number required in the function and ignore the remaining elements.

2. Joining/Appending iterables .

Using the spread operator, we can easily merge iterables, and save their properties into a new object.
For example;

var JohnScores = [75, 88, 69, 58, 92];
var SubScores =[92, 78, 36];

var UpdatedScore =[...SubScores, ...JohnScores];
console.log(UpdatedScore)

Enter fullscreen mode Exit fullscreen mode

In this example, we created another array called SubScores which stores the recent scores of the exams John wrote. We also merged the two arrays into a different array “Updated score” which would invoke

(8) [92, 78, 36, 75, 88, 69, 58, 92]

Enter fullscreen mode Exit fullscreen mode

We can also add an array inside another array


var JohnScores = [75, 88, 69, 58, 92];
var SubScores = [92, 78, 36, ...JohnScores];


console.log(SubScores);
Enter fullscreen mode Exit fullscreen mode

This would be the output on the console

(8) [92, 78, 36, 75, 88, 69, 58, 92]
Enter fullscreen mode Exit fullscreen mode

PS: The result of the joins depends on the order in which you include the array. For instance
If we log the JohnScores before the Subscores it would change the order and vice versa.


 var JohnScores = [75, 88, 69, 57, 92];


  var SubScores = [...JohnScores, 92, 78, 36];
  console.log(SubScores);

  var SubScores2 = [92, 78, 36, ...JohnScores];
  console.log(SubScores2);
Enter fullscreen mode Exit fullscreen mode
SubScores
(8) [75, 88, 69, 57, 92, 92, 78, 36] 
SubScores2
(8)[92, 78, 36, 75, 88, 69, 57, 92]
Enter fullscreen mode Exit fullscreen mode

3. Creating duplicate Objects

var John = {
    Name: 'John',
    Class: 'Grade1',
    Age: 19,
    Scores: [...JohnScores],
  };

  var John2 = {...John}
  console.log(John)
  console.log(John2)

Enter fullscreen mode Exit fullscreen mode

In the code snippet, we copied the object “John” using the spread operator into a new object “John2. Both John and John2 will have the same properties and values.

JOHN
{Name: 'John', Class: 'Grade1', Age: 19, Scores: Array(5)}
Age: 19
Class: "Grade1"
Name: "John"
Scores: (5) [75, 88, 69, 57, 92]
[[Prototype]]: Object

JOHN2
{Name: 'John', Class: 'Grade1', Age: 19, Scores: Array(5)}
Age: 19
Class: "Grade1"
Name: "John"
Scores: (5) [75, 88, 69, 57, 92]
[[Prototype]]: Object

Enter fullscreen mode Exit fullscreen mode

This allows us to clone objects easily without manually copying each property.

Rest Operators
Unlike the spread operators, rest operators allow us to combine individual elements as arrays. In cases where you want to create a function with an unknown number of arguments, you can use the rest operator to collect the extra inputs as an array.

For example, let’s create a function that accepts the price of groceries and computes the sum. Now we don’t know the exact number of groceries the user intends to buy so we would need to use a rest operator.

function sum(...prices) {
    let total = 0;
    for (let price of prices) {
      total += price;
    }
    return total;
  }


  console.log(sum(200, 400, 300, 550));

// OUTPUT ON THE CONSOLE WOULD BE 1450  

Enter fullscreen mode Exit fullscreen mode

In the preceding code, we created a function that accepts an unlimited number of prices using the rest operator(...prices) and loops through each price to get the total.
The rest operator collects all the possible prices and stores them in an array. The function then uses the for statement to loop through each price and computes the sum.

Rest Operators in Array destructuring.

Array destructuring means collecting values from arrays, or properties from objects and storing them into distinct variables.
Rest operators can also be useful when you want to extract some elements from an array and store the remaining elements in a single variable. For example, we have an array that stores the names of a Student.

 let Names = [Daniel, George, Bassey];

Enter fullscreen mode Exit fullscreen mode

From the preceding array, we see that the Student has three names, however, we can use the rest operator to take his first name and store the remaining names in another array.

let Names = ['Daniel', 'George', 'Bassey'];
const [firstName, ...otherNames] = Names;

console.log(otherNames);
Enter fullscreen mode Exit fullscreen mode

When this is invoked on the console, it would only show the names stored in the sub-array

(2) ['George', 'Bassey']
0: "George"
1: "Bassey"
length: 2
[[Prototype]]: Array(0)


Enter fullscreen mode Exit fullscreen mode

How to identify Spread and Rest operators.

From what we’ve learned, the spread and rest operators have the same (…) syntax so it might be quite confusing to differentiate them on a program. To resolve this you have to put this in mind.

  • Spread operators are typically used when you want to spread elements into a new array, function arguments, or object properties.
  • Rest operators are used to collect elements and condense them into one variable
  • Rest operators are typically used in the receiving location to capture multiple elements. For example, in function parameters or array destructuring.
  • The spread operator is typically used in the target location where elements are expected. For example, when creating a new array or object, or when passing arguments to a function.

Top comments (0)