admin管理员组文章数量:1394520
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
本文标签: Comparison operator giving idiosyncratic result in JavaScriptStack Overflow
版权声明:本文标题:Comparison operator giving idiosyncratic result in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744101638a2590897.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论