Reputation: 7729
If I use <= instead of <, I'll get NaN, why?
function addArgs(){
var sum = 0, count = 0;
while(count <= arguments.length){
sum += arguments[count];
count++;
}
return sum;
}
Upvotes: 0
Views: 149
Reputation: 1743
All iterations start from 0
(Also, count = 0
in your code). So, max count
equals arguments.length-1
.
addArgs(2,5,8);
-> arguments[0] = 2; arguments[1] = 5; arguments[2] = 8;
Besides that, you can use <=
when count
starts from 1
function addArgs(){
var sum = 0, count = 1;
while(count <= arguments.length){
sum += arguments[count-1];
count++;
}
return sum;
}
addArgs(2,3,4);//9
Upvotes: 1
Reputation: 877
Suppose your argument is 3 elements:
arguments = [0, 1, 2]
Your count will iterate as 0 => 1 => 2 => 3 (and on 3rd you are out of bound of the array, since it has 3 elements, but indexed starting with 0.
That's basics of iterating through loop.
Upvotes: 3
Reputation: 25341
When you iterate through a list and use the index to access the items of the list (like you're doing), you always iterate up to length - 1
or < length
. The reason is that the list index starts from zero, not one. For instance, a list of 3 items has it's length
equals 3 and the indexes of its items are 0, 1, and 2. There is no item with index 3, so if you iterate up to length
or <= length
, the counter will reach 3 in the last iteration and the attempt to retrieve the item with the index 3 will fail and return undefined
.
Finally, adding the undefined
to the sum will results in a NaN
because undefined
is not a number.
Upvotes: 2
Reputation: 19766
in the last iteration of your loop, count
is arguments.length
, therefore arguments[count] === arguments[arguments.length] === undefined
, and sum += undefined
results in sum === NaN
Upvotes: 3
Reputation: 31
It seems that arguments[count] is not a number (NaN). In Javascript, when the second argument in an expression is not a number, the first one is also treated as not a number.
Thus, sum ends up the function being treated as another data type.
http://www.w3schools.com/js/js_datatypes.asp
Upvotes: 2