JavaScript spread operator vs rest parameter -Major difference and Use Cases.

JavaScript spread operator vs rest parameter -Major difference and Use Cases.

What are spread operators and rest paremeters?

The spread operator and rest paremeter are important concepts used with arrays, functions and objects in JavaScript. A rest paremeter can be seen as an operator that allows you represent an unspecified number of arguments as an array. While the spread operator takes an iterable( strings, arrays, maps) and expand its elements one by one. Even though they both make use of three dots (...) they are quite different.

Same Syntax

(...) //rest parameter &spread operator JS syntax

The key difference between the spread operator and the rest parameter is that the spread operator does not put iterables or the remaining part of user input in an array, rather it expands the iterable into individual elements.

On the other hand, the rest paremeter does the opposite as it collects multiple elements and condenses them into an array. Simply put, with the spread operator you expand while with the rest paremeter, you compress.

Use cases of Spread Operator in JavaScript

After knowing the major difference between these two operators, it is important to know exactly where you can apply it. The spread operator takes all the elements from the array and it does not produce new variables. It is used in situations where we would otherwise write values seperated by commas and prominent in destructing arrays. Since the spread operator works on all iterables, it can serve several purposes.

The spread operator use cases include:

  • Copying an array/ obtaining individual element of new array

The spread operator can be use to copy the contents of an array to a new array with ease.

const champions =["Jinx", "Kalista", "Braum" ];
const newChampions= [...champions];

console.log(newChampions) //Output= ["Jinx", "Kalista", "Braum"];

If you prefer to get the individual element of the new array, all you need to is console.log(...newChampions) instead.

  • Merging two or more arrays together

Another use case for the spread operator is merging two or more arrays especially when you know the arrays you're working with.

const games = ["League of Legends", "VALORANT", "Fortnite"];
const developers= ["Riot Games", "Epic Games"];
const combined1 =[...games, ...developers];

console.log(combined1) //Output= ["League of Legends", "VALORANT", "Fortnite", "Riot Games", "Epic Games"]
console.log(...combined1) /*Output =League of Legends  VALORANT  Fortnite  Riot Games
Epic Games*/
  • Shallow Copying and Merging Objects

Just like with arrays you can also clone objects and merge two or more objects with spread operators.

//Shallow copy of objects with spread operator
const league ={
Lck: "Korea",
Lec: "Europe",
Vcs: "Vietnam",
Lpl: "China" }
const newLeague ={...league}; /*or*/ const newLeague2= {...league, Lcs:"North America"};

//Merging objects
const names ={
firstName:"Martin", 
gameName: "Wunder"}

const names2{
game: "League of Legends"}

const combinedObj= {...names, ...names2}

Note that you cannot expand objects with console.log(...combinedObj) as object properties are not iterable with just the spread operator itself.

  • Passing arguments into functions

The spread operator can also be used to pass multiple arguments to a function. When you pass several arguments with the spread operator, you don't have to worry if the arguments exceeds the specified paremeters as the function will take the needed arguments and ignore the remainder.

//3 paremeters specified below
function sum(a, b,c){
console.log(a+b+c);
}
const nums =[1, 2, 3, 4] //an array containing 4 numbers
sum (...nums) //function called with spread operator used to pass in four arguments.
Output =6 //The sum function will ignore the last number '4'.

Additionally, spread operators also works with strings as it returns each individual letters of the string either in array or as its own seperate element.

Use Case of Rest Paremeter in JavaScript

The rest parameter is commonly used in functions to pass an unknown number of paremeters to functons. The paremeter usually inputed as args is accessible within the function as an array. During the function call, you can then pass in multiple arguments which will return as an array.

function restUseCase(...args) {
console.log(args);}

restUseCase(1, 2, 3) //Output: [1, 2, 3]
restUseCase("Kennen", "Orn", "Fiora") //Ouptut: ["Kennen", "Orn", "Fiora"]

You can also add other parameters to a function before using the rest paremeter. Note that the keywords args can be replace with any preferred name pass to the function. However, it is advisable to stick with args as it will make it difficult for other developers to understand your code immediately. Moreover, only one rest paremeter can be used in a Javascript function.

Destructuring with spread operators and rest parameters

Destructuring is a way to break arrays and objects into smaller pieces in JavaScript. While you could easily access an individual element from a small array and copy it into a new array with the index, you will have to do that for every single element you want out of an array. Hence, it is much easier with destructuring.

//breaking down an array with the Index
const nums= [ 1, 2, 3, 4, 5, 6]
const numOne = nums[0] 
const numThree =nums[2]

//breaking down array with destructuring
const numsOne = [1, 2, 3, 4, 5, 6]
const [numOne, , numThree]= nums
//The extra comma skips the second number in the array as we want the first and third number only.

The spread operator and rest parameters allow for more use of destructuring as its hardly used on its own. With the rest paremeter, you can collect the elements not destructured into an array of its own.

const names =["Aatrox", "Ahri", "Akshan", "Akali", "Anivia", "Annie"]
const namesclone= [first, second, ...rest] = names

console.log(rest) //Output: ["Akshan", "Akali", "Anivia", "Annie"]

You can also use both the spread operator and rest operator to achieve a certain outcome in your code. Here, the rest paremeter will be used on the left while the spread operator is used on the right hand side while destructuring.

const restaurant = {
  name: 'Classico Italiano',
  location: 'Via Angelo Tavanti 23, Firenze, Italy',
 categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
mainMenu: ['Pizza', 'Pasta', 'Risotto', 'Rice']
}

//REST PAREMETER +SPREAD OPERATOR SYNTAX
const [foodOne, foodTwo, ...otherfood]= [ ...restaurant.starterMenu, ...restaurant.mainMenu]
console.log(foodOne, foodTwo, otherfood) 
/*Outuput:
 foodOne variable will output Foccacia  
foodTwo variable will output Bruschetta 
otherfood will output ['Garlic Bread', 'Caprese Salad', 'Pizza', 'Pasta', 'Risotto', 'Rice']
*/

So, the ...otherfood takes the rest of the food left in starterMenu and mainMenu spread operators and condenses them into a single array.

All in all, there are several use cases for the spread operator and rest paremeter and they always come in handy when you need them!