+ 3

When can we use javascript rest parameters

I recently came across a type of function in javascript that allows some undefined amount of parameters to be supplied when called, the code looks like this function restFunc (...params){ console.log(params.length); } please note that params not restricted to arrays only, and I wonder why would there be a need for such a function, where you don't even know what parameter to expect into your function, can someone please provide a use case for such example https://code.sololearn.com/WhYiORIqil95/?ref=app

6th Jan 2018, 6:18 PM
olufemi jolugbo
olufemi jolugbo - avatar
3 Antworten
+ 5
One use case of variable length parameters would be when you have a string, within which you have placeholders, (e.g. ...%1...%2...%3...) you need to replace those placeholders with real values, and you want the function to be dynamic, it should be able to work with a string having different number of placeholders, sometimes there's one, some other time three, and so on, so, instead of having to write several functions with different number of replacement string parameters, you take this approach : )
6th Jan 2018, 7:50 PM
Ipang
+ 4
@Olufemi Jolugbo, I cannot create a code in JavaScript, my device is too old it doesn't even understand what those ... in the function argument : ) But I can make one with PHP, since it's run on the server, so here it is, I'm sure you can understand the logic, and then you can try to implement it in JavaScript on your side. https://code.sololearn.com/wQyVrsO87774/?ref=app
7th Jan 2018, 7:13 AM
Ipang
+ 1
good attempt at explanation @ipang, perhaps a code sample to illustrate this would be perfect
6th Jan 2018, 8:03 PM
olufemi jolugbo
olufemi jolugbo - avatar