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
Add a ment  | 

3 Answers 3

Reset to default 2

To 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