JavaScript Quiz: is this equal to that?

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.

Image for post
Image for post

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.

Image for post
Image for post

Thanks for reading!

And remember: grit > talent.

Always learning.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store