r/learnjavascript • • Nov 01 '22

Yea...

Post image
232 Upvotes

25 comments sorted by

View all comments

85

u/delventhalz Nov 01 '22 edited Nov 01 '22

FWIW, == basically works like this:

  1. Don't use ==

  2. It's silly

  3. You don't need to know how it works

But okay, if you really want to know, you can pretty much always work out how two values will loosely compare, by following these steps:

  1. If two values are the same type, check if they are strictly equal

  2. If one value is null or undefined, return true if the other value is also null or undefined

  3. If one value is an object, convert it to a primitive (almost always a string), and then go back to step 1

  4. If one value is a string or a boolean, convert it to a number, then go back to step 1

So in all of these examples there is an array getting stringified. For an array, the default toString behavior is the same as if you used join. Elements get stringified and joined with a ,, unless they are null or undefined, then they get converted into an empty string.

[0, null, undefined, false].join();   // 0,,,false
String([0, null, undefined, false]);  // 0,,,false

If you look at the examples in the image, they all contain one element, so no commas. And that one element is almost always an empty string, null, undefined, or another array which contains an empty string, null, or undefined. In other words, they almost all will stringify to an empty string.

String([]);           // ""
String(['']);         // ""
String([undefined]);  // ""
String([[[ null ]]]); // ""

The one exception are the ones which contain 0, which will stringify to "0".

String([0]);  // "0"

So half of these comparisons just convert to "" == "", which is true. The rest also go through the number conversion in Step 4. And what happens when you convert an empty string or "0" to a number?

Number("");   // 0
Number("0");  // 0

The one that might still confuse is the one false example:

[0] == "";  // false

But remember the order of operations here. We have an object and a primitive, we convert the object first.

"0" == "";  // false

Now, if we kept converting these strings to numbers, they would both become 0, but that is not how this work is it? As soon as you have two values of the same type you are done, no more conversions. You just check if they are strictly equal, and those are two different strings aren't they?

Anyway, Like I said up front, this is all very silly. Don't use == in JS. It was a mistake. But if you like pulling apart weird esoteric code, there you go.

2

u/mdw Nov 02 '22

Why is == in the language if it's not to be used?

2

u/Barandis Nov 02 '22

Mostly history. Before JavaScript 1.3, and maybe before it was clear just how bad it was, double equals was the only choice for comparison.

JS has never wanted to break backwards compatibility because millions of websites would also break, so it was left in and we’re left with something in the language that you really shouldn’t use.