0

often time I have this pattern problem in javascript. I have an add function

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

then I can do add(1,2) //3

but what if I want to pass in any length of arguments?

I can't do freely add(1,2,3,4). or add(something,something,something). If I want I have to write another add function that accept 4 and 3 arguments.

I know I can use loop them up by loop but how to pass any number of argument to a function in js?

Jessie Emerson
  • 743
  • 4
  • 12
  • 25
  • 1
    So loop over the arguments https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments – epascarello Dec 06 '16 at 13:45

2 Answers2

1

you can use arguments property .

function add(){
  var sum=0;
  for (var key in arguments)
    sum=sum+arguments[key];
 return sum;
}
console.log(add(1,2,3,7));
Mahi
  • 1,707
  • 11
  • 22
1

You can loop over arguments and add values

ES6

function add(){
  return Array.from(arguments).reduce((p,c)=>p+= !isNaN(c)? +c : 0, 0)
}

console.log(add(1,2,3,4,5))
console.log(add(1,2,3,'a', 7))

ES5

function add(){
  return [].slice.call(arguments).reduce(function(p,c){
    p+= !isNaN(c)? +c : 0;
    return p;
  }, 0)
}

console.log(add(1,2,3,4,5))
console.log(add(1,2,3,'a', 7))
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79