Search code examples
javascriptarraysbooleancomparison

Empty array is truthy or not in JavaScript?


I'm a bit confused by the following results, could someone kindly point out what happened under the hood? why Boolean([]) will return true? and loosely compare empty array to a Boolean [] == false would evaluate to true?
but strict comparison would evaluate to false??

This is the part I don't get it

Thanks so much!

Boolean([])
//true

[] == false
//true

[] === false
//false

Solution

  • Boolean([]) // => true
    
    • Here, [] (Array is object type) is converting to boolean. Since [] has the reference value, after conversion is is true.

    .

    [] == false // => false
    
    • Here, Equality operator loosely check values. Since both sides are different types (object and boolean) and one of side is boolean, So it will covert to (0 or 1) and compare to other side. It will be equivalent to +[] == +false, which will be 0 == 0, will be true

    Check MDN document for more details

    [] === false // => false
    
    • Here, Strict Equality operator. Will check for Type and value Since both are different types, it will be false.