What is the fastest way to sum up an array in JavaScript? A quick search turns over a few different methods, but I would like a native solution if possible. This will run un
The fastest loop, according to this test is a while loop in reverse
var i = arr.length; while (i--) { }
So, this code might be the fastest you can get
Array.prototype.sum = function () {
var total = 0;
var i = this.length;
while (i--) {
total += this[i];
}
return total;
}
Array.prototype.sum adds a sum method to the array class... you could easily make it a helper function instead.