Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I check if an array is empty with array == []?

This is a question from CodeWars that is named "Count of positives/sum of negatives". It says:

If the input array is empty or null, return an empty array

To check if the array is empty, I decided to check if it was an empty array. When I try to do:

if(input == [])

I fail the test, but if I do:

if(input.length == 0)

I pass the test. An empty array should be equal to [] right? Why is there a difference, and what is the difference between these two checks?

My code is as follows:

function countPositivesSumNegatives(input) {
   var a = 0;
   var b = 0;
   if (input == null) {
      return []
   }
   if (input.length == 0) {
      return []
   }
   for (var i = 0; i < input.length; i++) {
      if (input[i] > 0) {
         a++;
      }
      if (input[i] < 0) {
         b += input[i];
      }
   }
   return [a, b]
}
like image 389
Ellen Avatar asked Jun 06 '17 04:06

Ellen


1 Answers

The problem is that arrays are objects. When you compare two objects, you compare their references. Per the MDN documentation:

Equality (==)

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

Since two instances of arrays don't necessarily have the same reference, the check fails. Just try this in the console:

> [] == []
false

Two arrays seemingly with the same content (or lack thereof) are not equal. That's because content is not checked, but reference. These two arrays are separate instances and refer to different places in memory, thus the check evaluates to false.

On the other hand, just checking the length, and if it is zero checks if the array is empty or not. The length property signifies the amount of content in an array1 and is part of every array. Since it is part of every array and reflects the amount of data in the array, you can use it to check if the array is empty or not.


1 Beware, though, of sparse arrays as mentioned by RobG in the comments. Such arrays can be created with new Array(N) which will give you an empty array, but with length N.

like image 113
Andrew Li Avatar answered Nov 14 '22 01:11

Andrew Li