Hello Guys today i want to show you how you can use rest parameters in javascript and i will try my best to explain this concept to you
Let's get started...
What is Rest Parameter?
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.
Let's understand this with a bunch of code examples
// normal function
function normalRestParameter(...rest){
for (let i of rest) {
console.log(i)
}
}
normalRestParameter(10,20,30,40,50)
//10,20,30,40,50,60
//anonymous functions and here we have used
//reduce method of Array means we can use
//array methods on rest parameters
let anonymousFunction = function(...rest){
const output = rest.reduce(
(previousValue, currentValue) => previousValue + currentValue, 0);
return output
}
console.log(anonymousFunction(1,2,3,4,5))
// 15
//arrow function example 1
let arrowFunction1 = (...rest) => console.log(rest)
//arrow function example 2 using rest parameter
//with normal parameters , the first two parameters
//will be a and b and the rest will be assigned
// to an array of parameter
let arrowFunction2 = (a,b,...rest) => {
console.log(a,b,rest)
}
arrowFunction1(1,2,3,4,5,6)
//[1,2,3,4,5,6]
arrowFunction2(1,2,3,4,5,6)
//1 2 [ 3, 4, 5, 6 ]
//getting the length of rest parameter
const lengthRestParameter = (...rest) => {
console.log(rest.length)
}
lengthRestParameter(1,2,3,4,5,6,7,8,9,10)
//10
//using array methods like sort
const sortedRestParameters = (...rest) => {
console.log(rest.sort((a,b) => a - b))
}
sortedRestParameters(6,9,4,10,2,8,5,7,1,3)
//[1,2,3,4,5,6,7,8,9,10]
//DO NOT USE Rest parameter at statrting
// or middle position always use it at
// the end of the parameters
function wrongRestParameter1(...rest,a,b){
console.log(rest)
}
wrongRestParameter1(1,2,3,4,5)
//SyntaxError: Rest parameter must be last formal parameter
//DO NOT USE More than 1 rest parameter
function wrongRestParameter2(...rest1,...rest2){
console.log(rest1,rest2)
}
wrongRestParameter2(1,2,3,4,5)
//SyntaxError: Rest parameter must be last formal parameter
As you can see some examples of using the rest parameter in different scenarios.
THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--
Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo
https://dev.to/shubhamtiwari909/e-quotes-3bng
https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl
Top comments (3)
Nice explanation!
Just adding the reference of rest parameters 😁
Best regards
Actually the examples i created was not copied i created them and run them just to check is there any exceptions or not
And i found that while using the sort method 10 comes before other numbers so, i had to use the (a,b) => a-b approach to sort them correctly because we all know this is JAVASCRIPT king of exceptions 😂😂
Thank you 😂😂