1

A friend of mine today told me to open the Chrome Console and see the output for three JavaScript commands that I report here below (with the corresponding output).

> Boolean([])
< true
> Boolean("")
< false
> [] == ""
< true

When I told him that it was probably a bug, he replied that it is a famous thing and a JavaScript developer should know about it.

Is it true? Is there any logic that justifies the output seen above or it is just a bug of the language?

Nisba
  • 3,210
  • 2
  • 27
  • 46

3 Answers3

2

To compare [] and "", JavaScript tries to bring them to same type, in this case: String.

You'll notice a similar result with this (and it makes sense to us):

[].toString() == "" // true
mehulmpt
  • 15,861
  • 12
  • 48
  • 88
2

Wow! What a great question! This is such crazy behavior when coming to JavaScript from a different language right? Or heck, even if JavaScript is your first language it's still crazy. But it is indeed the language working as intended.

There's an amazing answer/explanation of this behavior and why it happens here. In a nutshell, JavaScript does a lot of type casting and interesting things under the hood when you use the equality operator (==). More often, you'll probably want to be using the identity operator (===) as it performs stricter comparison and JavaScript doesn't attempt to do any type-casting or magic beneath the surface when using it.

Alex
  • 64,178
  • 48
  • 151
  • 180
2

Double equals performs type coercion. It'll attempt to convert each one to a common type before checking equality. This is why it's recommended JavaScript developers always use triple equals(===) which performs a strict type equality comparison.

In this case, [] will be converted to an empty string which is considered falsy like the empty string it's being compared to. The same situation can be seen in the example below:

[5]==5
true
webnetweaver
  • 192
  • 8