JavaScript Equality Operators Explained Visually

JavaScript Equality Operators Explained Visually
In: JavaScript

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.

JS Object Equality
Your favorite jsconsole.

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?

Assigning one of the chicks to another variable and comparing again.
Assigning one of the chicks to another variable and comparing again.

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?

Your objects in memory.
Your objects in memory.

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.

JavaScript Equality for Primitives

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.

javascript loose equality under the hood

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! 🐣

Comments
More from RichStone Input Output
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to RichStone Input Output.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.