Sure you can see a reflection, you can see a picture, a friend can describe it to you in detail for hours, but you can never perceive your face directly.
Great. What does this have to do with Javascript?
Well, the other day I was practicing solving algorithms, and I stumbled across something that was a bit mystifying. I was trying to do this:
arr.find(el => el === [2,3])
It returned undefined even though I was looking at the input data and knew that there was a matching element. After triple checking everything else around this find() method I knew it must have something to do with the comparison operators and how Javascript treats arrays. I found a solution for this particular problem:
arr.find(el => el.length === 2)
But I made a note to come back to it later and here we are. My first step to clearing this up was to hop in the console and play around with array comparison a bit:
let test = [2,3]
undefined
test == [2,3]
false
typeof test === typeof [2,3]
true
test === [2,3]
false
[2,3] === [2,3]
false
Hmmm, seems like two arrays with the same values in the same order are not equal to each other. My reflection isn't my face!
Well, sort of. After a bit of digging, turns out that the comparison operators are only meant to work on primitive data types. When you use them on objects or arrays(which inherit from Object) Javascript returns true only if the compared values refer to the same instance. So:
let a = {name: "bob"}
let b = {name: "bob"}
a === b
false
a === a
true
b === b
true
//but you can always do
a.name === b.name
true
//because both name properties return strings
Which makes a lot of sense. Objects and Arrays are structured datatypes, and if you want to compare two instances for equality you should consider exactly what it means for two Arrays or Objects to be equal. The answer will be different depending on the situation. In certain situations, you may want to consider two arrays equal that have the same elements but in a different order. In other situations, you may want to consider two objects not equal because one has the k/v name: null
and another has the k/v name: undefined
.
So there you have it. If you want to compare objects or arrays, just remember you need to loop through their values in a way that will allow you to use the comparison operator on primitive datatypes.
Top comments (1)
The term you are looking for is "deep equality"