How JavaScript compares objects by reference, not value.

I Thought I Knew JavaScript… Until I Compared Two Objects 😅 🚀 Today I learned something that seems simple at first — but it completely changed how I think about JavaScript objects! In JavaScript, objects, arrays, and functions are compared by reference, not by value. That means: const obj1 = { a: 1, b: 2 } const obj2 = { a: 1, b: 2 } console.log(obj1 === obj2); // false Even though they look identical, they’re actually stored in different memory locations. Each time you write { a:1, b:2 }, you’re creating a new object in memory. However, if you assign one object to another variable: const obj1 = { a:1, b:2 }; const obj2 = obj1; console.log(obj1 === obj2); // true Now both variables reference the same memory address — so a change in one reflects in the other. Understanding this subtle difference between reference and value comparison helped me better grasp how caching, memoization, and equality checks work under the hood in JS. Takeaway: Objects are shared by reference, but compared by memory address. #JavaScript #WebDevelopment #Learning #CodingJourney #TechInsights

Great insight! I've learnt something similar, comparing two NaN values always returns false. console.log(NaN === NaN); // ❌ false Why: According to IEEE floating-point rules, NaN is not equal to anything, including itself. It's confusing yet interesting if we go deeper to understand why js behaves weirdly.

To view or add a comment, sign in

Explore content categories