What's the output?

MediumQuince

Prompt

What's the output of the following code?

let obj1 = {};
let obj2 = {};
console.log(obj1 == obj2); // ??
console.log(obj1 === obj2); // ??

Solution

The Curious Case of == vs ===

Hey there! Let's dive into why both those comparisons return false and what's really happening behind the scenes. This is actually a super common source of confusion when working with JavaScript objects.

let obj1 = {};
let obj2 = {};
console.log(obj1 == obj2); // false
console.log(obj1 === obj2); // false

What's Going On Here?

When we create those two empty objects with , JavaScript does something really important: it creates two completely separate objects in memory. Even though they look identical (they're both empty!), they're stored in different locations in your computer's memory.

Think of it like this: imagine you have two identical blank notebooks. They might look the same, contain the same number of pages, and be completely empty - but they're still two different physical notebooks sitting in different places on your desk.

Reference vs. Value

This is what we call reference comparison in JavaScript. When comparing objects, JavaScript doesn't check what's inside the objects - it checks if they're the exact same object in memory.

To continue our notebook analogy, JavaScript isn't saying "do these notebooks contain the same stuff?" Instead, it's asking "are these literally the same physical notebook?"

Loose Equality (==) vs Strict Equality (===)

Now you might be wondering - "Wait, I thought == and === were different?" And you're right!

  • The === operator checks both type and reference without any type conversion
  • The == operator normally does type conversion between different types

But here's the interesting part: when comparing two objects with either operator, they behave exactly the same way. Both check if the objects are the same reference in memory.

When Would Objects Be Equal?

For two objects to be considered equal using either operator, they need to reference the exact same object:

let obj1 = {};
let obj3 = obj1; // obj3 points to the same object as obj1

console.log(obj1 == obj3); // true
console.log(obj1 === obj3); // true

Here, we're not creating a new object for obj3 - we're just creating another variable that points to the same object that obj1 points to.

00:00

Table of Contents