The code snippet below can be really confusing.
if ([]) {
  console.log([]==false)
}
- If [](empty array) is truthy then why is[]==falseevaluating 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!!
 
![Cover image for Is [ ] truthy in JS ?](https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fxkasvrf0pcrhedwv72yt.png) 
              
 
    
Top comments (0)