JavaScript Quiz: is this equal to that?

Saul Feliz
2 min readJun 2, 2020

--

What’s this REALLY pointing to?

Consider these two arrays:

const arr1 = [1, 2, 3];
const arr2 = [3, 2, 1];

If you did,

console.log(arr2.sort())

You’d get [1, 2, 3]

But if you did

console.log(arr1 === arr2.sort());

You’d get false back. Same if you didn’t do a strict (==) comparison.

Here’s why Britney…

While outputting arr1 and arr2.sort() both print out the same thing ([1, 2, 3]), they actually refer to different positions in memory. And that’s really what the equality operators do. They answer: are these two objects pointing to the same position in memory?

Another way to test this would be by doing this:

console.log(arr2 === arr2.sort());

This would evaluate to true. Because while arr2 and arr2.sort() would print out different things, their relative position in memory is the same thing.

Unfortunately, unlike Python, JavaScript lacks an easy way to get the unique identifier for a position in memory for a given variable. But using some of the methods outlined here you can infer what’s going on under the hood.

Thanks for reading!

And remember: grit > talent.

--

--

Saul Feliz
Saul Feliz

No responses yet