I'm wondering why my conditional statement where I'm trying to sort out the edge case of the input array being empty doesn't seem to work. With my current test case, the result I get is NaN (no idea why). If I change the conditional to if (array.length === 0)
, then my code functions the way I want it to. Isn't []
the correct representation of an empty array though?
function getAvg(array) {
if (array === []) {
return 0;
}
var sum = 0;
var average = 0;
var length = array.length;
for (var i = 0; i < length; i++) {
sum += array[i];
}
average = sum / length;
return average
}
var input = [];
var result = getAvg(input);
console.log('should be 0:', result);