Reputation: 29
<script>
function range (start , end ) {
var list =[]
for (var count = start ; count <= end ; count++)
list.push(count);
return list
}
function sum ( nums ) {
var total = 0;
for ( var count = 0 ; count <= nums.length ; count++ )
total = total + nums[count];
return total;
}
console.log(range(1 , 10))
console.log(sum(range(1 ,10)))
</script>
When I run this, the output from my sum
function will be NaN
. I know the solution is to remove the =
from the sum
function however I do not understand how this solves the problem.
Upvotes: 1
Views: 54
Reputation: 976
when you <= that means you are including the end number. all arrays are 0
indexed, meaning the first item is at index 0
for an array of 10 items, this means the the last index is 9
also for incrementing an existing number you can use +=
function range (start , end ) {
var list =[]
//here you want INCLUSIVE because you are starting
//at VALUE 1 and ending at VALUE 10
for (var count = start ; count <= end ; count++)
list.push(count);
return list
}
function sum ( nums ) {
var total = 0;
//here you want EXCLUSIVE because you are starting
//at INDEX 0 and ending at INDEX 9
for ( var count = 0 ; count < nums.length ; count++ )
total += nums[count];
return total;
}
console.log(sum(range(1,10)))
Upvotes: 1
Reputation: 124648
You are iterating beyond the bounds of the nums
array.
As such, in the last iteration of the loop you effectively execute total = total + undefined
, the result of which is NaN
.
Try for example in a JavaScript console, n + undefined
results in NaN
, where n
is any number.
Change the loop condition to count < nums.length
instead of <=
:
for ( var count = 0 ; count < nums.length ; count++ )
total = total + nums[count];
Upvotes: 5