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);

2
  • 1
    TLDR; [] is a new different empty array, not the representation of any empty array. Think object references. Commented Aug 4, 2021 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. Commented Aug 4, 2021 at 17:05

1 Answer 1

0

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

 if(arr.length>0){}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.