Done#Having Trouble in loop function Sum All Numbers in a Range

Done#Having Trouble in loop function Sum All Numbers in a Range
0

#1

Tell us what’s happening:

Having prob with for loop. Cannot sum? why

Your code so far

function sumAll(arr) {
        var total;
        var a = Math.max(arr[0],arr[1]);
        var b = Math.min(arr[0],arr[1]);
        //console.log(b);
  for (var i = b; i >= a; i++) {
   		console.log(total =+ i);
      return total;
  }
  
}

console.log(sumAll([1, 4]));
sumAll([1, 4]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36.

Link to the challenge:


#2

Incorrect syntax.
Must be:

+=

#3

doesnot work…Buti change all expression like this… here i didi as you write. i want to push all iteratied numbers insie sum array. cannot, could you help

function sumAll(arr) {
        var total;
        var sum = [];
        var a = Math.max(arr[0],arr[1]);
        var b = Math.min(arr[0],arr[1]);
        //console.log(b);
  for (var i = a; i >= b; i--) {
   		total  += i;
       console.log(sum.push(total));
  }
  return sum;
}

sumAll([1, 4]);

#4
function sumAll(arr) {
  var total, c;
  var summ = [];
  var a = Math.max(arr[0], arr[1]);
  var b = Math.min(arr[0], arr[1]);
  //console.log(b);
  for (var i = a; i >= b; i--) {
    total += i;
    summ.push(i);

  }
  //console.log(summ);
  var result = summ.reduce(function(sum, value) {
    return sum + value;
  }, 0);
  return result;
}



sumAll([1, 4]);

#5
for (var i = b; i >= a; i++) {
 return total; 
}

You return inside your loop. It will exit the function sumAll() on the first iteration with the value b.


#7

Well. I learnt it just after doing it . looked on solved examples by others. Realised i just wrote longer. But exactly why? can you explain plz? why as empty array it did not accumulate it?
because