1

In David Flanagan's Javascript guide, there is a statement:

the == operator never attempts to convert its operands to boolean

So here I did a little test:

var a = false;
var b = ""; // empty string
a == b; //returns true

Looking at Abstract Equality Comparison Algorithm there is a point:

e. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.

How can x and y be both true if y is string data type (without conversion)?

johnnyRose
  • 7,310
  • 17
  • 40
  • 61
Alexander Kucheryuk
  • 606
  • 1
  • 8
  • 16
  • "If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y." followed by "If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y)." – zerkms Aug 08 '15 at 01:12
  • Related: http://algorithmicassertions.com/visualization/2014/03/27/Better-JS-Equality-Table.html and http://www.impressivewebs.com/why-use-triple-equals-javascipt/. – jarmod Aug 08 '15 at 01:14

1 Answers1

6

What happens under the hood is

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

Number(false) == ""

followed by

If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

Number(false) == Number("") -> 0 == 0

How can x and y be both true if y is string data type (without conversion)?

They are not both true, but after type coercion their values are equal.

the == operator never attempts to convert its operands to boolean

And that is correct, if you check the comparison algorithm you will find that types are never implicitly casted to Boolean.

References:

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • Thanks for pointing out my mistake - I obviously misunderstood the question. +1 for an *actual* answer. ;) – johnnyRose Aug 08 '15 at 01:23
  • Small question. Though equality operator itself doesn't do any conversion, ToNumber does. Since equality operator uses ToNumber function, wouldn't technically this mean that equality operator converts ? – Alexander Kucheryuk Aug 08 '15 at 12:20
  • @AlexanderK. it converts passed values implicitly to some general type, that's right. – zerkms Aug 08 '15 at 12:33
  • In that case, it seems the original statement by Flanagan is not technically correct, isn't it? What I mean is, while equality operator itself doesn't do any conversion, it uses functions as a part of its algorithm that do conversion. – Alexander Kucheryuk Aug 08 '15 at 19:33
  • @AlexanderK. it is correct, during that conversion a particular operand value is never casted to a boolean. He did not say that during `==` operator application no conversions are performed, but said that no conversions to booleans are performed. – zerkms Aug 08 '15 at 20:41
  • Ah, brilliant! I keep forgetting that he is being specific about conversion to booleans, not in general. – Alexander Kucheryuk Aug 08 '15 at 22:10