rest and spread operators in JavaScript

Rest and Spread Operators in JavaScript with examples

Rest and Spread Operators are essential parts of JavaScript. JavaScript has always had the capability of passing functions with or without parameters without any issue.

The default parameters allow you to accept fewer parameters while still assigning values to the remaining parameters.

Many current programming languages allow functions to accept a variable number of parameters. With Rest Parameters, ES6 adds this much-needed feature to JavaScript.

You can now pass a function with a variable number of parameters very easily. If you wanted to do this in ES5, you’d have to store all of the values in a data container data type, such as an array.

Let’s look at an example,

let items = function (id, ...collection) {

items(42, "books", "papers"); 

// ["books", "papers"]

The three-dot(… ) symbol is the rest symbol. It comes before a named argument. This named parameter will be converted into an Array that will include all of the remaining parameters supplied to the function. As a result, Collections is set to an array in this case.

The Rest parameter collects all of the parameters that follow the id parameter and stores them in an array.

Everything, with the exception of the first defined argument ‘id,’ will be placed in the Array.

When we execute the same function with only one parameter, the id, it returns an empty array [].

Let’s have a look at the function’s length property. The number of parameters in the method may be obtained by items.length.

let items = function (id, ...collection) {

items(42, "books", "papers");

//output: 1

The length property ignores the Rest parameter. In the above situation, the answer is 1. The function’s length property only counts the number of named parameters omitting the rest parameter.

Now consider the case where we verify the arguments.length within the function:

let items = function (id, ...collection) {
items(100, "books", "papers"); 

// output: 3

The Spread Operator

The spread operator, which is also indicated by… before an array, performs the opposite operation of the rest operator. It spreads an array and transfers its contents to the specified function. Consider the following scenario:

let List1 = [10, 20, 30, 40];
let newList = [0, ...List1, 50]

// output: [0, 10, 20, 30, 40, 50]

The rest parameters allow you to combine numerous arguments into a single array. whereas the spread operator allows you to provide a single array. The array can be split into individual arguments so you can pass them into a function or method.

The spread operator makes it considerably easier to handle parameters supplied to a function as arrays. like the rest operator, you can use the spread operator in a function constructor as well.