I recently had some small problems with an app that I'm making, and it turns out that I realized that one of the things that made what I was doing not work well is that, at a certain moment when iterating through values of a JSON, and compare each of the values with another JSON with the same properties but different values, I realized that one of the comparisons that I made in the cycle was an empty array with another empty array (If that content did not exist within that array or if it had just been initialized as an array), something like this:
let myJson = {
title: "cualquier titulo",
content: "cualquier contenido",
links: []
}
let myJson2 = {
title: "cualquier titulo 2",
content: "cualquier contenido 2",
links: []
}
Obviously at a certain point when comparing the links of json1 with json 2, translating it to how I would see it or compare the if, I have something like:
if([] == []){
//Instrucciones que no se ejecutaran
}
However, then I am left wondering why this returns false??, that is, both are arrays, both have the same length and both do not have any value inside, why does it return false then?
Javascript, like Java or C#, considers that no two objects are equal, because what you're really comparing is the pointer to the object. Therefore,
==
or===
they only serve to compare primitives or to know if the object is exactly the same:An important detail to keep in mind: In Javascript there is the primitive type
string
(which does not exist in Java, for example), and also the String class:Here he explains it clearly.
Basically, what it says is that an empty array is only strictly equal to itself. That is, the evaluation of a reference to an empty array is only strictly equal to the same reference pointing to the same empty array.
In the case you have, you have two empty arrays with two different references (one pointing to each one), and since each reference is different from each other, the comparison between them is
false
.To try to clarify it better, if you look at the image below, you will see how variable1 (reference to an object) is different from variable2 (reference to an object with the same values but different in memory).
However, if the two variables pointed to the same region of memory, then they would be the same.
A simple example to understand this would be the following:
The same thing happens for any object, not only for arrays, and although it may seem the same to you, for javascript it is not.
Unfortunately there is no way to re-implement the comparison operator, so you would have to make a specific function to compare them manually.