The Spread Operator and the Rest parameter (...)

Introduction

The spread operator and the rest parameter are new concepts in JavaScript introduced in ES6, both have three dots as their sign, however, they are not the same. The spread operator helps to expand an iterable into individual elements while the rest parameter allows you to spread an iterable object and pass its parts into a new array.

In this article, I will explain how the spread operator and the rest parameter works with vivid examples.

Table of contents

  • The spread operator (...)
  • The rest parameter (...)
  • Conclusion
  • References

Prerequisite

You should be familiar with loops and functions

The spread operator(...)

In the introductory paragraph, I stated that the spread operator expands iterables. An iterables is an array, maps, sets, etc. Now let's work with some examples

creating a new array from an existing array Example 1:

const arr = [4, 5, 6, 7];
//use the spread operator to add elements to the array above, creating a new array

const newArray = [1, 2, 3,  ...arr];
console.log(newArray); // [1, 2, 3, 4, 5, 6, 7]

///to log the individual element of the newArray, do this
console.log(...newArray); // 1 2 3 4 5 6 7

Example 2:

const artist = {
  name: 'Taylor  Swift',
  location: 'Nashville, Los Angeles, New York',
  albums: ['Red', 'Folklore', 'Speak Now', 'Reputation'],
  release: [2021, 2020, 2019, 2017],

  order: function(album1, release1) {
    return [this.albums[album1], this.release[release1]];
  }
};


//We want to update the albums array above to create a new one

const newAlbums = [...artist.albums, 'Evermore'];
console.log(newAlbums); // ['Red', 'Folklore', 'Speak Now', 'Reputation', 'Evermore']

Note that we are creating a new array not manipulating the old one

The spread operator can be used to copy and merge arrays

Example 3:

To copy an array

const releaseCopy = [...artist.release];
//here we want to copy the contents in the release array into a new array named releaseCopy
console.log(releaseCopy); //[2021, 2020, 2019, 2017]

To merge an array

Let's merge the albums array and the release array

const mergedArray = [...artist.albums, ...artist.release];
console.log(mergedArray); // merges the two arrays into one

The spread operator on strings

Example 4:

const name = 'john';
const str = [...name, 'y'];

console.log(str);//logs ['j', 'o', 'h', 'n', 'y']

We can also use the spread operator on objects

Example 5:

Now we want to add more properties to the original artist object to create a new artist object

const newArtist = {age: 32,  ...artist, awards: 'grammy'}
console.log(newArtist); //logs a new artist array with the new properties

We can do the COPY method on objects too

Example 6:

const artistCopy = {...artist}; //copies the artist object into artistCopy object
console.log(artistCopy);

The REST parameter(...)

The rest parameter allows you to spread an iterable object and pass its parts into a new array. What this means is that The REST parameter(...) instructs the computer to add the rest of the (supplied) values into an array.

Example 1:

let [firstName, lastName, ...otherInformation] = [ "Temi", "Shola", "Designer", "Web Developer", "Female" ]; 

 console.log(otherInformation) // logs Temi Shola [Designer Web Developer Female]

In this example, the rest parameter took out the first two elements from the array and put the rest of the elements in a new array.

Notice that in the rest parameter example, the three dots(...) are on the left-hand side of the equal sign while in the spread operator the three dots(...) are on the right-hand side of the equal sign.

Example 2:

Using this artist object, let's first merge the albums and release array together, then we destructure it, take out 'Red', 'Speak Now', and then use the rest parameter to log the rest of the elements into a new array

const artist = {
  name: 'Taylor  Swift',
  location: 'Nashville, Los Angeles, New York',
  albums: ['Red', 'Folklore', 'Speak Now', 'Reputation'],
  release: [2021, 2020, 2019, 2017],

  order: function(album1, release1) {
    return [this.albums[album1], this.release[release1]];
  }
};

const [Red, , Speak Now, ...otherss] = [...artist.albums, ...artist.release];

console.log(Red, SpeakNow, otherss);// logs Red SpeakNow [new array]

Example 3:

Rest parameter in objects using destructuring

What if we want to take out the value of august

  const artist = {
  name: 'Taylor  Swift',
  location: 'Nashville, Los Angeles, New York',
  albums: ['Red', 'Folklore', 'Speak Now', 'Reputation'],
  release: [2021, 2020, 2019, 2017],

  releaseTime: {
    march: {
      day: 12,
      hour: 13,
    },
    august: {
      day: 23,
      hour: 10,
    },
    june: {
      day: 16,
      hour: 24,
    },
  }
};

const {august, ...time} = artist.releaseTime;
console.log(august, time); //logs {day: 23, hour: 10} and the rest of the months

Rest parameter using functions

In this function, we want to take an arbitrary amount of argument and all together

const addAll = function(...numbers) {
  let sum = 0;
  for(let i = 0; i < numbers.length; i++)
  sum += numbers[i];
console.log(sum);
}
addAll(1, 6, 9, 25);  // 41

The rest parameter made it possible for the function to be able to add all the numbers together.

Conclusion

The concept of the spread operator and the rest parameter has been discussed in this article with concrete examples to help you grasp it better.

We have learned that the spread operator helps to expand an iterable into individual elements while the rest parameter allows you to spread an iterable object and pass its parts into a new array.

References