While testing some new code at Experience, I noticed what feels like an inconsistency in array to boolean conversions in JavaScript.

To prove the difference, here are the situations I looked at:

  // Straight Equality
[] == true; // false
[] == false; // true

// Conversion
Boolean([]); // true
! Boolean([]); // false

// Implied Conversion
! []; // false
!! []; // true

As you can see, the first straight equality checks behave as if an empty array is false, which is common in back end languages, such as Groovy. However, transposing an empty array to a boolean asserts it to be true, which is consistent with using the forced conversion with the bang operator (!).

Why this matters is that using an if statement behaves in the latter case, which sets an empty array to true. Lessons learned from this experiment are to always check if an array is empty (through a .length call) to determine if the logic should succeed.


3,761 0 4