DEV Community

Cover image for Rest Parameter and Spread Operator in JavaScript
Ayobami Ogundiran
Ayobami Ogundiran

Posted on • Updated on

Rest Parameter and Spread Operator in JavaScript

The Rest Parameters and Spread Operator are some of the great features that come with ES6 and make life easy for JavaScript users.

It is now relatively easy and interesting to group parameters and merge multiple objects or arrays.

Now, let's dive deeper.

Spread Operator (...)

Three dots (...) before an iterable( array or string ) denotes what we call "The Spread Operator".

It is used to unpack the elements or properties of an object or array and list them one by one from the beginning to the end within another array or object.

Merging two or more arrays or objects

We can merge two arrays or objects with the use of the spread operator as in:

Array example
let eProductPrices = ["$10", "$23", "$40"];

let physicalProductPrices = ["$70", "$80", "$100"];

let prices = [...eProductPrices, ... physicalProductPrices]
Enter fullscreen mode Exit fullscreen mode

We have merged the arrays.

Object example
let gadgetsQuotation = {phone: "$1000", laptop: "$2000"};

let otherQuotation= { banana: "$300", massage: "$390"};

let quotations = {...gadgetsQuotation,...otherQuotation};
Enter fullscreen mode Exit fullscreen mode

Yeah! We have merged two objects into a new one.

Coping elements of an array or object to another

Hey, wait!

I want to ask you a stupid question because there is a sense in nonsense.

I want to copy all the elements of an array called "firstNumberList" to another array called "secondNumberList".

How can I do that with the spread operator?

Never mind! Check below:

Array example
let firstNumberList = [1, 2, 3, 4];
let secondNumberList = [ ...firstNumberList ]

console.log( secondNumberList ) // [1, 2, 3, 4];
Enter fullscreen mode Exit fullscreen mode
Object example
let schoolProperties = { cheap: true, position: "1st"};
let properties = {...schoolProperties};

console.log(properties) // { cheap: true, position: "1st"};
Enter fullscreen mode Exit fullscreen mode

We use the spread operator to copy the properties of the "schoolProperties" to "properties". So, they now have similar elements.

Using the spread operator in a function call.

Sometimes, we may have an array or object we want to pass its elements or properties as parameters to a function one by one. In that case, we can use the spread operator as in:

let multiplyThreeNumbers = (firstNumber, secondNumber, lastNumber) => firstNumber * secondNumber * lastNumber;
Enter fullscreen mode Exit fullscreen mode

In the above code, multiplyThreeNumbers takes three parameters and it multiplies them.

It is possible to spread the elements of the "numbers" array as the arguments to multiplyThreeNumbers as in:

Array example
let numbers = [1, 2, 3]
multiplyThreeNumbers( ...numbers); //6
Enter fullscreen mode Exit fullscreen mode
Object example
let numbers = {firstNumber: 1, secondNumber: 2, lastNumber: 3}
multiplyThreeNumbers( ...numbers);// 6
Enter fullscreen mode Exit fullscreen mode

In short, we can use the spread operator to spread the elements of an array or properties of an object as arguments to call a function.

Yeah! You can spread everywhere

let numbers = [1, 2, 3, 4];

//At the beginning:
let spreadAtTheBeginning = [...numbers, 5, 6];
console.log(spreadAtTheBeginning) // [1,2,3,4,5,6]

//At the middle
let spreadInTheMiddle = [5, ...numbers, 6];
console.log(newNumbers) // [5, 1, 2, 3, 4, 6]

//At the end
let spreadAtTheEnd = [5, 6, ...numbers]
console.log(spreadAtTheEnd) // [5, 6, 1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

In short, you can use the spread operator at the beginning, middle and end of an array or object.

The Rest Operator (...)

The rest operator gathers the remaining parameters or elements into an array.

Packing remaining parameters with the rest operator

Parameters can be passed into a function as in:

let add3 = ( firstNumber, secondNumber, thirdNumber) => firstNumber + secondNumber + thirdNumber; 
Enter fullscreen mode Exit fullscreen mode

Sometimes, we may want to pack all parameters of a function to an array for some reasons, then we can use the rest operator to pack the parameters into an array as in:

let add3 = (...theRest) => theRest.reduce( (accum, oneOfTheRest) => {
   console.log(theRest); 
   return accum + oneOfTheRest;
});

console.log(add3(4, 5, 6)) // 
Enter fullscreen mode Exit fullscreen mode

"...theRest" packs parameters passed to the function into an array and that is why we can easily use reduce on it as in above example.

Before the introduction of es6, I did use "arguments" in place of the rest parameters as in:

function add3() { console.log(arguments) }

add(4,5,6); // 
Enter fullscreen mode Exit fullscreen mode

Yeah! It works.

Hey, wait! There is a problem.

The array created with the arguments keyword is an array-like object. That is to say, it is not really an array because it doesn't have all the array methods.

So, we cannot do:

function add3() { 
   arguments.reduce( function(accum, oneOfTheRest){
   console.log(theRest); // [4, 5, 5] 
   accum + oneOfTheRest;
  }
}

add(4,5,6); // Uncaught TypeError: arguments.reduce is not a function
Enter fullscreen mode Exit fullscreen mode

Oops! You can't do that.

Also, the fat arrow function (=>) doesn't have the arguments keywords. That means "arguments" is not available in the fat arrow function.

Let's see how it goes:

let multiply = () => console.log(arguments);

multiply()//Uncaught ReferenceError: arguments is not defined
Enter fullscreen mode Exit fullscreen mode

Oops! It is not accessible just like the air of "yesteryears".

Defining some parameters before the rest parameters

When creating a function, we can pass some parameters before using the rest operator as the last parameter as in:

let merge = (firstNumber, ...theRest) => [firstNumber, theRest];

console.log(merge(2,3,4,5,6)); [2, [3, 4, 5, 6]];
Enter fullscreen mode Exit fullscreen mode

"firstNumber" is an element on it own but other arguments are packed into an array as we can see in the above example.

The rest(...) always come alone or last

"The rest always come alone or last" is a statement to remember we only use the rest parameters alone or last.

What will happen if it doesn't come alone or last?

See it for yourself as in:

let subtract = (first, ...second, third) => console.log(second);

subtract(1,2,3,4) //Uncaught SyntaxError: Rest parameter must be last formal parameter
Enter fullscreen mode Exit fullscreen mode

Oops! It doesn't work.

Hey, trust me, I am lying.

Oh! Sorry, trust me, I am right.

The rest as an operator in destructuring

The rest (...) can be used as an operator in destructuring as in:

let [first, second, ...theRest] = [ 1, 2, 3, 4, 5, 6];

console.log(theRest) // [3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

That is it.

The rest and spread operator make it easy to deal with parameters and variables in JavaScript.

Hoooooooooooorrah!

See you in the next lessons.

One more thing

Are you having difficulties to learn and understand JavaScript and build projects with it? JavaScript for a Total Novice teaches JavaScript and Project Making Fundamentals with simple illustrations and examples that make everything so easy. You can now handle any difficult projects without fear.

Don't trust me, get a free previous to judge by yourself: https://bit.ly/3o3TMyg

Top comments (0)