TIL Equality in JS
POSTED ON:
TAGS: javascript wat
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: javascript