A friend of mine today told me to open the Chrome Console and see the output for three JavaScript mands 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?
A friend of mine today told me to open the Chrome Console and see the output for three JavaScript mands 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?
Share Improve this question asked Apr 14, 2018 at 19:19 NisbaNisba 3,4765 gold badges33 silver badges56 bronze badges 2- dmitripavlutin./the-legend-of-javascript-equality-operator – u_mulder Commented Apr 14, 2018 at 19:20
- 1 type casting... – mehulmpt Commented Apr 14, 2018 at 19:23
3 Answers
Reset to default 2To pare []
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
Wow! What a great question! This is such crazy behavior when ing 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 parison and JavaScript doesn't attempt to do any type-casting or magic beneath the surface when using it.
Double equals performs type coercion. It'll attempt to convert each one to a mon type before checking equality. This is why it's remended JavaScript developers always use triple equals(===) which performs a strict type equality parison.
In this case, [] will be converted to an empty string which is considered falsy like the empty string it's being pared to. The same situation can be seen in the example below:
[5]==5
true