For languages like Python, or PHP comparing two completely empty arrays returns True as it is
[] == []
either
[] === []
Why is it not the same for JavaScript, are they different elements? Or what happens??
For languages like Python, or PHP comparing two completely empty arrays returns True as it is
[] == []
either
[] === []
Why is it not the same for JavaScript, are they different elements? Or what happens??
This is not exclusive to JavaScript, the same problem appears in other programming languages because it would be comparing the instance of the object/array and not the value itself.
So
[] == []
actually doing the first one[]
is not equal to the second[]
one because they are not the same instance. Each of them[]
will have a different identity. As you suggest in the question, they really are different elements.And if
[] == []
it's false, then[] === []
it will also be false because, even if the type were the same, the identity is different.Reference (in English):
When you do
[]
this creating a new array object is the equivalent of doingnew Array()
is like shorthand, you can see that they are different objects with the Object.is commandFor obvious reasons if it
==
is false, doing===
it will return the sameFor them to be equal the variable must be pointing to the same object, but when you make a change the other variables will take the change (mutable objects)
[] turns out to be false, example
but they are of different types, we test with ===
Now we compare, but we cannot compare directly
array1==array2
, we must compare the elements, for that we usejoin();
I tell you the following so that within JavaScript when comparing two arrays, even if they are empty, it returns true; You must make use of the typeof() function so that in this way they are not only compared perhaps in length but also in type:
You can also notice that in JS arrays are objects in fact everything is an object out there could be the answer
If you want to obtain a TRUE when comparing two arrays you can, for example, put values to each one and at the moment of making the comparison do it by its length as in the following case
To the previous example, if at the moment of comparing you remove access to the length method and make the comparison, it will give FALSE
Greetings, I hope to make myself understood
From what I read out there, it is because of how arrays are treated, in javascript it is in a different way, although for example you do this
will give you the result false because to compare
array
you need to treat it in a different way such as looping through it or applying a property to treat the array.so if i run this it will return true