Sum All Numbers in a Range(Help with magic)for a noob

Please help me understand

I am having a hard time understanding why this works. It seems to me that I would be reset to 1 each pass of the loop. I knew this solution would work, but i dont understand why it does.

function sumAll(arr) {
var total = 0;
for (var i = Math.min(...arr); i <= Math.max(...arr); i++){ total += i; }

return total;
}

sumAll([1, 4]);

Each iteration of the loop update your total variable, so you have:

total = 0 + 1 // first iteration 
total = 1 + 2 // second
total = 3 + 3
total = 6 + 4 // at this point i <= 4 is true for last time so after this the loop breaks, and the final result is total = 10

i used the console to check that out as i went, and i could see how it was getting the right numbers, but the first part of the loop var i = Math.min(...arr) sets the value of i to 1 each time it passes because 1 is the lowest value in the array. Obviously that's not what happens, but it seems like it should be. I just don't understand how it it keeps the value given to it after its incremented with i++. so it seems like it should go on forever.

Not everything in the parentheses is executed each loop. The first expression is the initializer and only gets executed once, at the start of the looping process. The second expression is evaluated every loop testing for false, so that the for-loop knows when to stop. The third expression is executed at the start of each loop also (typically used to increment a counter that is tested in the second expression).

2 Likes