Patonza Patonza - 11 months ago 34
Javascript Question

Empty arrays seem to equal true and false at the same time

Empty arrays are true but they're also equal to false.

var arr = [];
console.log('Array:', arr);
if (arr) console.log("It's true!");
if (arr == false) console.log("It's false!");
if (arr && arr == false) console.log("...what??");


Array: []
It's true!
It's false!

I guess this is due to the implicit conversion operated by the equality operator.

Can anyone explain what's going on behind the scenes?


You're testing different things here.

if (arr) called on object (Array is instance of Object in JS) will check if the object is present, and returns true/false.

When you call if (arr == false) you compare values of this object and the primitive false value. Internally, arr.toString() is called, which returns an empty string "".

This is because toString called on Array returns Array.join(), and empty string is one of falsy values in JavaScript.