Antonio Ortiz Antonio Ortiz - 5 months ago 14x
Javascript Question

How do I sum all the numbers in a range using this function in JavaScript?

I am working through this coding challenge on Free Code Camp

We'll pass you an array of two numbers.
Return the sum of those two numbers and all numbers between them.
The lowest number will not always come first.

They suggest to use
Math.max(), Math.min(), Array.reduce()
, however I began working through a solution which did not use any of those methods—but soon discovered maybe I should have because my version began to look a little clunky.

function sumAll(arr){
var index0 = arr[0], index1 = arr[1], counter = 0, sum = 0, val;
if(index0 < index1){
counter += index0;
while(counter <= index1){
val = index0++;
sum += val;

} else if(index0 > index1){
counter = 1;
counter += index0;
while(counter >= index1){
val = index1 + 1;
sum += val;
return sum;

Basically this works save for when you try:

sumAll([10, 5]) //I get 42, rather than 45

So my two questions are the following:

Am I correct in the fact it's getting clunky?
And should I have used the aforementioned methods which were recommended?
I think I just got excited when stuff when I got things to work but now I feel I am going down a rabbit hole with another potential condition..

Thanks in advance!


You could use min, max and one loop

var sumAll = function(arr) {
  var sum = 0,
    min = Math.min.apply(null, arr),
    max = Math.max.apply(null, arr);
  for (var i = min; i <= max; i++) {
    sum += i;
  return sum;
console.log(sumAll([10, 5]))