3

I have a large numbers of variables. What is the most correct way to calculate the sum. Below is the static way. .What if the numbers will increase to N times?

function abc(a,b,c,d){
  alert(a+b+c+d); 
}
abc(2,3,4,5);
2
  • 8
    Why don't you use an array instead of a large number of variables? Will make adding up easy. Commented Jul 27, 2013 at 19:47
  • 1
    Where are the numbers coming from? User input? Commented Jul 27, 2013 at 19:49

4 Answers 4

4
function abc(){
    return Array.prototype.reduce.call(arguments, function(a,b) {
        return a + b;
    }, 0);
}

We can reduce the verbosity by binding .reduce as the this value of .call.

var reduce = Function.call.bind([].reduce);

Then it's just:

function abc(){
    return reduce(arguments, function(a,b) {
        return a + b;
    }, 0);
}
Sign up to request clarification or add additional context in comments.

Comments

3

You could use arguments

function abc(){
  var total = 0;
  for( var i = 0; i < arguments.length; i++) {
     total += arguments[i];
  }
  alert(total);
}

abc(1, 2, 3, 4, 5, 6, 7);

Demo

OR

function abc( args ){
  var total = 0;
  for( var i = 0; i < args.length; i++) {
     total += args[i];
  }
  alert(total);
}
abc([1, 2, 3, 4, 5, 6, 7]);

Demo

The best way would be to use the latter.

4 Comments

The arguments array isn't deprecated in strict mode, but strict mode does change it and remove some behavior.
arguments haven't been deprecated or removed. arguments.caller was, but it was replaced with arguments.callee.caller
The .arguments property on a function object is prohibited in strict mode.
@JanDvorak: arguments.callee is also prohibited in strict.
2

To accept a limitless number of arguments automatically, use the arguments property.

function sum() { // javascript functions can accept more arguments than specified
  var total = 0;
  for (var i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

Bear in mind that this might not actually be much shorter or more-readable than just calling "a + b + c + d" in your original code.

Comments

1

Here is a shorter version using the Array.reduce() command.

function abc() {
   alert([].reduce.call(arguments, function(a, b) { return a + b; }));
}
abc(2,3,4,5);

1 Comment

Crazy Train posted the same solution while I was testing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.