4

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
1
  • Empty array in javascript is truthy inorder to check for array you have to check the length of array if ([].length) {// do something } else {// do something else} Commented Jul 1, 2020 at 3:58

2 Answers 2

10

The easiest way to check reliably is to use the length property.

[].length // 0, falsy

['something'].length // 1. truthy

See the official spec for more info.

Sign up to request clarification or add additional context in comments.

2 Comments

but 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
Its not all logical. See the above linked repo. There are many example of these things that are just crazy. It's goof to know they are there when looking for a weird error though.
4
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.

2 Comments

THANKS! Concise explanation
@siva Please correct [] == false // => false.. you added it not false its true some typo

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.