DEV Community

Matsu
Matsu

Posted on • Edited on

Unveiling a JavaScript Trick: Array Comparison Pitfall

Have you ever come across a JavaScript interview question that left you scratching your head? Here's a little trick that might catch you off guard:

const a = [1, 2, 3];
const b = [1, 2, 3];
console.log(a === b);
Enter fullscreen mode Exit fullscreen mode

What do you think the result will be on the console? It might seem logical to expect true, but the actual answer is false! Intrigued? Let's unravel this mystery.

The Expectation: True?
At first glance, comparing arrays a and b using === might lead you to believe that the result should be true. After all, both arrays seem identical, containing the same elements in the same order.

The Reality: False!
The surprising reality is that JavaScript's strict equality (===) checks for reference equality, not content equality. In other words, it's comparing the memory addresses of the arrays, not their actual content.

Why It Happens
Arrays, being reference types, create distinct instances in memory even if their content is the same. Hence, a === b evaluates to false because a and b refer to different memory locations.

The Solution: Content Equality
If you want to compare arrays based on their content rather than their reference, you can use JSON.stringify():

console.log(JSON.stringify(a) === JSON.stringify(b)); // true
Enter fullscreen mode Exit fullscreen mode

This approach converts the arrays to JSON strings, allowing for a content-based comparison.

JavaScript's array comparison can be a subtle trap, and understanding the difference between reference equality and content equality is crucial. The next time you encounter a similar scenario, you'll be armed with the knowledge to navigate through the trickery.

Console You Later!

Top comments (0)