Reputation: 115
I am trying to create a JavaScript (pure) function that averages an array of numbers. No error is returned, but it always returns NaN. What is wrong? Here is my code:
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
function average(datasetArr) {
var totalSum;
var x;
for (x in datasetArr) {
totalSum = datasetArr[x] + totalSum;
}
var average = totalSum / datasetArr.length; //keeps returning NaN
console.log(average); //In the console: returns: "NaN"
}
average(arr);
Does anyone have any working code snippets or improvements to my code?
Upvotes: 0
Views: 107
Reputation: 2864
In your example you have not initialize the totalSum variable with 0.
You can use this way too.
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
function average(datasetArr) {
var average = datasetArr.reduce((result, current) => result += current, 0) / datasetArr.length;
console.log(average);
}
average(arr);
Upvotes: 1
Reputation: 1898
You need to initialize totalSum
to 0
If you don't initialize it, you are trying to add a number to undefined
for example 3 + undefined
will evaluate to NaN
On a side note, you can use Array.prototype.reduce to sum an array
var array = [1, 2, 3, 4];
var sum = array.reduce((a, b) => a + b, 0);
console.log(sum); //10
Upvotes: 2
Reputation: 906
You have to set the totalSum
variable to 0 first. If you don't set it to zero, you cannot add datasetArr[x]
to totalSum
inside the for loop.
Solution:
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
function average(datasetArr) {
let totalSum = 0;
for (let x in datasetArr) {
totalSum = datasetArr[x] + totalSum;
console.log(totalSum)
}
var average = totalSum / datasetArr.length;
console.log(average); //In the console: returns: "NaN"
}
average(arr);
Upvotes: 0