DEV Community

Cover image for Is [ ] truthy in JS ?
Som Shekhar Mukherjee
Som Shekhar Mukherjee

Posted on

Is [ ] truthy in JS ?

The code snippet below can be really confusing.

if ([]) {
  console.log([]==false)
}
Enter fullscreen mode Exit fullscreen mode
  • If [](empty array) is truthy then why is []==false evaluating to true?
  • 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
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

Thanks!!
You can follow my (Instagram page)[https://www.instagram.com/js.cruise/] for more such amazing content.

Top comments (0)