Member-only story
Mystery behind JS array Equality ( === )
Lets us understand the mystery
Equality operators (==
or ===
) both work differently for objects (Type of array
is an object
in JS ) when compared to other primitive types.
const a = 1;
const b = 1;
console.log(a == b) //true
console.log(a === b) //true
console.log(1 === 1) //true
console.log(1 == 1) //true
As you can see when we compare the two numbers, we are able to get true
as expected and straight forward.
const a = [1];
const b = [1];
console.log(a == b) //false
console.log(a === b) //false
console.log([1] === [1]) //false
console.log([1] == [1]) //false
console.log(a == [1]) //false
console.log(a === [1]) //false
console.log(a == a) //true
console.log(a === a) //true
We just wrapped the same number to array, suddenly we are getting false , which is not the usual expectation.
As mentioned earlier, we are actually comparing the references not values, incase of object
typeof [1]
— object
typeof 1
— number
So be careful when you are comparing array (and object) in javascript.
So how to compare the values of the array
If order of the elements should be matched, we can compare by converting to string
JSON.stringify(a) === JSON.stringify(b)
If elements can be of any order in both the arrays, we can do the following
a.length === b.length && a.every((value, index) => value === b[index])
we have to iterate with every element in the array and ensure every element on each side is equal