How can I have an infinite parameter function in javascript?


I'm not sure of how many arguments to pass to a function and it must do the same functionality irrespective of number of arguments.

for example:

function sum(a,b) {
  return a+b;
}

sum(1,2);
sum(1,2,3,4);
sum(1,2,3,4,5,6);

I want to use the same sum function to pass any number of arguments. Is there any simple way to do it?

1 Answer

5 years ago by

ES6 introduced spread operator(...) which does amazing things in Javascript. In this example, it accepts any number of arguments and check the below example for understanding it's usage.

function sum(...args) {
  return args.reduce((a,b)=> a+b);
}

console.log(sum(1,2))

console.log(sum(1,2,3,4))

console.log(sum(1,2,3,4,5,6))

5 years ago by Jahaan