The code snippet below can be really confusing.
if ([]) {
console.log([]==false)
}
- If
[]
(empty array) is truthy then why is[]==false
evaluating totrue
? - If
[]
is falsy then why is the code entering the if block? Let's answer both these one by one.
The following are the only falsy values in JavaScript:
false
-
""
(empty string) 0
NaN
null
undefined
So, []
is definitely not falsy
Why is the code entering the if block?
The code is entering the if block because JavaScript is trying to coerce []
to a Boolean which results in being true
.
console.log(Boolean([])) // true
Why []==false
is true?
Equal (==)
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
So, one of the operands here is a Boolean, so JavaScript will try to convert both the operands into Numbers and do a strict comparison. Since both Number([])
and Number(false)
give 0
, the comparison will become true
.
console.log([]==false)
// This is similar to:
console.log(Number([])===Number(false))
Thanks!!
You can follow my (Instagram page)[https://www.instagram.com/js.cruise/] for more such amazing content.
Top comments (0)