JavaScript Equality Operators Explained Visually
I still learn new things about equality in JS. There's plenty to keep in mind when you try to compare primitives and objects for equality. Let's look at the basics of how the JS "strict equality" (===
) and "loose equality" (==
) operators compare objects and primitives. Let's also peek at why they work like that.
Starting with object equality. Imagine that you work on a farm software. Your farm has chickens. For every new chick that's born and scanned an object is created. Most chicks don't have any special traits, so you decide to make them very simple JSON objects for now.
Comparing newly created JSON objects inside the console returns false
in both cases (with ==
and ===
), although you could probably expect that at least the ==
would be less strict.
When would we ever get true for objects then?
So basically, you'll get true
if the object (a JSON object, an array, a function, etc.) is the exact same object. With objects, ==
and ===
don't check for structure.
But what does "the exact same object" mean?
Now the primitives. Some of those chicks in your farm enjoy a little primitive treat every now and then, like a cigarette. Some play nice and have a gum cigarette, others are badasses and enjoy real smoke.
You decide to be cool and represent a real cigarette with a "1"
and a sweet cigarette with a 1.
As you can see, the "loose" equality operator ==
is less strict ;)
If you've ever wondered what the logic behind this magic is, it's actually just some boring rules that are written in C.
Now that you know how to compare your chicks and their cigs for equality and why ==
| ===
work how they work, you are a step away from saving the world! 🐣