Marciano - 1 year ago 81
Javascript Question

# Javascript : The sum of its range

I'm currently following the exercises from Eloquent Javascript and got a little stuck at one exercise. Let me explain it with code:

var _numberArray = [];

function range(start, end, step)
{
console.log(_numberArray);

if (!step)
{
step = 1;
}

if (step < 0)
{
for(var i = start; i >= end; i -= step)
{
_numberArray.push(i);
console.log(_numberArray);

}
}
else
{

for(var i = start; i <= end; i += step)
{
_numberArray.push(i);
console.log(_numberArray);
}
}

return _numberArray;
}

function sum(array)
{
var total = 0;
for (var i = 0; i < array.length; i++)
{

total += array[i];

}

}

console.log(sum(range(42,14,-2)));

So I created the range function where I check if the step argument has been set. If not, set the default step variable to 1. If step is smaller than 0, be sure to loop where as long as the first argument is bigger the second, and decrement the value with the step amount given. This is the same for incrementing.

However, this code causes to crash only when I use negative values. So when I do "sum(range(22,6,-2));" the code crashes. The other way round "sum(range(6,22,2));" it does work. Also when I replace:

for(var i = start; i >= end; i -= step)
{
_numberArray.push(i);
console.log(_numberArray);

}

For:

for(var i = start; i >= end; i--)
{
_numberArray.push(i);
console.log(_numberArray);

}

It does work again! Can someone help me out and give me some understanding why it crashed and why the last method does work?

Thanks.