Today I Learned - Rocky Kev

TIL Equality in JS

POSTED ON:

TAGS:

Description:
Strict Equality: a === b (triple equals).
Loose Equality: a == b (double equals).
Same Value Equality: Object.is(a, b).

console.log(Object.is(2, 2)); // true
console.log(Object.is({}, {})); // false

Mental Modeling example:

const continents = 7;
const dwarves = 7;
const luckyNumber = "7";

console.log(Object.is(continents, dwarves)); // true
console.log(Object.is(continents, luckyNumber)); // false

So why does {} === {} //false?

Because each {} creates a different value.
Think of it this way.

const thingsAboutJohn = {};
const thingsAboutSarah = {};

thingsAboutJohn === thingsAboutSarah; // false

This will not work either:

let ticket = { id: 0 };

if (ticket === { id: 0 }) {
console.log("Bad Ticket");
}

Remember - it's a new object!

Instead, do this:

let ticket = { id: 0 };

if (ticket.id === 0) {
console.log("Bad Ticket");
}


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.