Spread vs Rest Operator in JavaScript

Both Rest and Spread Operator in JavaScript use the ... operator as syntax. What is the Rest Operator? What is the Spread Operator? Read on to learn

Spread vs Rest Operator in JavaScript

Using the ... operator is a feature introduced in ES6 JavaScript. The ... operator is used for both the spread and rest operators in JavaScript, but these operators aren't the same.

What is the Spread, and What is the Rest operator in JavaScript? Is there any difference between these two operators? This guide explains everything you need to know about JavaScript's spread vs. rest operator.

Let's get started!

The Spread Operator

The spread operator expands iterable into individual elements. It is used to split groups of values into individual values. Examples of groups of values include strings, arrays, and objects.

When used on strings and arrays, the spread operator returns an array but returns an object when used on an object.

The ... operator is the syntax used for the spread operator. See it at work.

let randomString = 'Akande Olalekan Toheeb'

let arrayOfStrings = [...randomString];

console.log(arrayOfStrings); // returns (22) ['A', 'k', 'a', 'n', 'd', 'e', ' ', 'O', 'l', 'a', 'l', 'e', 'k', 'a', 'n', ' ', 'T', 'o', 'h', 'e', 'e', 'b']

Uses of the Spread Operator

The Spread operator is used in four contexts: array expressions, string expressions, object expressions, and function expressions.

Here's a breakdown of what the spread operator is used for in the above contexts.

  • Concatenation: The spread operator concat strings, arrays, and objects. It's possible to add two arrays together, It's possible to add two strings, and it's possible to add two objects. Additionally, you can add an array or a string to an object; the result will be an object.
    The spread operator can replace the .push() method to add new values to arrays. The spread operator also replaces the .concat() method used to concat arrays in JavaScript. Below are some examples:
// Addition of two Strings
let progLang = 'JavaScript';
let qualifier  = ' is fun.'

let newStr = [...progLang, ...qualifier];

console.log(newStr); // ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't', ' ', 'i', 's', ' ', 'f', 'u', 'n', '.']

// Addition of two arrays
let arr1 = ['JavaScript'];
let arr2 = ['is fun.'];

let newArr = [...arr1, ...arr2];

console.log(mySpread); // ['JavaScript', 'is fun.']

// Addition of two objects
const flying = { wings: 2 }
const car = { wheels: 4 }
const flyingCar = {...flying, ...car}
console.log(flyingCar) // {wings: 2, wheels: 4}

// An Array and An Object
let progLang = ['JavaScript'];
let fullName = {
  fname: 'akande',
  lname: 'toheeb'

let profile = {...progLang, ...fullName};

console.log(profile); // {0: 'JavaScript', fname: 'akande', lname: 'toheeb'}

// Add new members to arrays without using the push() method
let veggies = ['onion', 'parsley'];
veggies = [...veggies, 'carrot', 'beetroot'];
console.log(veggies); // ['onion', 'parsley', 'carrot', 'beetroot']
  • Convert a string to an array: The spread operator makes it possible to convert a string into an array. The spread operator is far better in string conversion to an array than in the .split() JavaScript method. For instance,
//Using the spread operator
const progLang = "JavaScript";
const arrayOfChars = [...greeting];
console.log(arrayOfChars); // ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']

// Using .split()
const progLang = "JavaScript";
const arrayOfChar =progLang.split(' ');
console.log(arrayOfChar); // ['JavaScript']

The first part of the code snippet uses the spread operator to convert the string to an array. The result is more satisfying compared to the second part, which uses the .split() JavaScript method.

  • Copy an array or an object into a separate one: Copying either an array or an object is easy with the spread operator. Here's how to do it:
// Copy an object into a separate one
const car1 = {
    speed: 200,
    color: 'yellow'
const car 2 = {...car1}

car1.speed = 201

console.log(car1.speed, car2.speed)
  • Replace .apply() JavaScript method: The spread operator can replace the .apply() method in JavaScript. .apply() is used in most cases where the elements of an array are to be used as function arguments. It copies the array's elements and is further used as the function argument. To demonstrate,
function myFunction(x, y, z) {
  let result = x + y+ z;
const args = [0, 1, 2];
myFunction.apply(null, args); // 3

With the spread operator, the above can be written as:

function myFunction(x, y, z) {
  let result = x + y+ z;
const args = [0, 1, 2];
myFunction(...args); // 3

There are many more tricks that you can perform with the spread operator. Some of them are handy when working with a library such as React.

The Rest Operator

The rest operator, as the name implies, is used to get all of the remaining values of a specific group of values into an array. Compared to the spread operator that spreads values, the rest operator is the opposite. The rest operator compresses values.

The rest operator is used mostly in functions with uncertainty about the number of arguments to be passed. Most importantly, a JavaScript function must have only one rest operator.

The rest operator uses the same syntax as the spread operator, the ... operator.

Uses of the Rest Operator

The rest operator has only one use: to put the rest or remaining values of a specific group of values into an array.

Example of the rest operator at work:

function devData(fname, lname, email, level, ...otherInfo){

devData('Akande', 'Olalekan', 'akandeolalekantoheeb94@gmail.com', 'intermediate', 'Technical writer', 'Codecada', 23); // ['Technical writer', 'Codecada', 23]

The function above has four params, three are standard params, and the last is with the rest operator. There's uncertainty about the information required, thus, the need to use the rest operator.

otherInfo will be an array of the remaining values after the three other params have taken their values. In this example, it has ['Technical writer', 'Codecada', 23].

\>Using 'use strict' inside a function containing the rest operator is prohibited. Using 'use strict' directly will only account for unimaginable errors. For this reason, 'use strict' can be used indirectly outside the function if it's important to use it in the code snippet.

To Sum Up

The spread and the rest operators make working with strings, arrays and objects easier. The spread operator spreads values while the rest operator compresses them. The spread operator can be used many times in a function that is converse to the rest operator; the rest operator can only be used once in a function.

What's more?

Nothing, this guide covered all.

Happy coding 🥳!