I can't figure out why my conditional statement to handle the edge case of an empty input array is not working as expected. When I test it with my current example, it returns NaN (no clue why). However, if I change the conditional to if (array.length === 0)
, then my code works perfectly. But shouldn't []
be the correct way to represent an empty array?
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);