Reputation: 777
I wanted to create a basic function summing up values from an array. I'm aware of the array reduce method but i wanted initially to use a loop "for" instead as below...however it returns NaN...why ?
var numbers=[1,2];
var total;
function sum(array){
total=0;
for(var x=0;x<=array.length;x++){
total += array[x];
}
return total;
}
Upvotes: 0
Views: 62
Reputation: 36703
Do sum(numbers)
, also in your loop the break condition should be x<array.length;
also you do not need to make total
a global variable to continue adding values of array to it.
var numbers = [1, 2];
function sum(array) {
var total = 0;
for (var x = 0; x < array.length; x++) {
total += array[x];
}
return total;
}
var total = sum(numbers);
alert(total);
Though the shorter way will be to use .reduce on the array
var array = [1,2]
var sum = array.reduce(function(prev, curr) { return prev + curr; }, 0);
alert(sum);
Here You can also provide an Arrow Function instead of a full function.
var array = [1, 2]
var sum = array.reduce((prev, curr) => prev + curr);
alert(sum);
Upvotes: 1
Reputation: 2922
You get NAN because, as the loop's condition isx<=array.length
, the last iteration adds array[length]
to the sum, while the last item of the array is array[length - 1]
Upvotes: 0
Reputation: 92854
If you want to stay on your initial approach, then you don't have to return global variable from within function. You can change global variables inside function directly;
var numbers=[1,2],
total;
function sum(array){
total=0;
for(var x = 0, len = array.length; x < len; x++){
total += array[x];
}
}
In other cases, of course, using of local variables is preferable when you intend to form independent results
Upvotes: 0