0

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);
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
KGE
  • 125
  • 10
  • 1
    TLDR; `[]` is a new different empty array, not the representation of any empty array. Think object references. – Ayush Gupta Aug 04 '21 at 16:57
  • You are getting NaN because the array length is 0, which means (sum / length) is 0 / 0 which is NaN because you can't divide by zero. – nullromo Aug 04 '21 at 17:05

1 Answers1

-1

You can check if length of array is greater than 0\

 if(arr.length>0){}
Dibash Sapkota
  • 617
  • 5
  • 8