Introduction
Javascript is one of the most used programming languages, and nearly 95% of websites use javascript. Javascript has plenty of features that help developers to handle and manipulate the data.
Arrays are one of the most used data structures in Javascript, so most of the time, you, as a javascript developer, would be handling the data in arrays. To ease the data handling and manipulation, rest parameters and spread syntax were introduced in ES6.
In this blog, we will be discussing rest parameters and spread syntax in detail, along with some examples.
Also Read About, Javascript hasOwnProperty
Rest Parameters
Rest parameter is an effective and enhanced way to handle the parameters. It allows us to handle the parameters of a function easily. The rest parameters allow us to handle and represent the indefinite input as an array. With the use of rest parameters, a function can be called with any number of arguments
Syntax:
function fun(...parameters) //... is the rest parameters
{
}
To understand the rest parameters in detail, let’s take a look at an example to add numbers without rest parameters and with rest parameters.
//without rest parameters
function add(a,b)
{
return a+b;
}
console.log(add(1,2)); //3
console.log(add(1,2,3,4,5)); //3
One thing to note in the above code is that it will not throw any error even when we are passing arguments more than what is defined in the function signature, but the first two arguments would be taken, and the code will execute. While with the use of rest parameters, any number of arguments can be taken, and we can do what we want.
//with rest parameters
function add(...input)
{
let sum=0;
for( let i of input)
{
sum=sum+i;
}
return sum;
}
console.log(add(1,2)); //3
console.log(add(1,2,3,4,5)); //15
Using the rest parameters, we are able to get the sum of any arbitrary number of input parameters.
But one important point to keep in mind while using rest parameters is the rest parameter must be the last argument of function as its work is to collect all the remaining parameters.
For example, the following code will throw an error on execution.
// function will throw error
function fun(a,...b,c){
console.log("Wrong function defination");
}
fun(1,2,3,4,5);