I was asked to write a function sortByFoo in Javascript that would react correctly to this test :
// Does not crash on an empty array
console.log(sortByFoo([]) === []);
But I've tried something :
[] === [];
>> false
Just so I can be sure, such a test would always fail, no matter the sortByFoo function, wouldn't it ? But I'd like to have an explanation on why this happens. Why [] isn't identical/equal to [] ?
Please forgive my approximate english, it is not my native language :p
Because every time you write
[]
you are calling array's constructor.[]
is the same asnew Array()
, and in Javascript new objects compared with equals method are different. See the reference, it is the same asnew Object()
when using{}
.Yes, you are correct that two array literals are never equal. That's because they are references to two separate instances of arrays.
The code to describe the test should be written:
Checking that the reference returned by the function is the same that was sent in, and that the array is still empty, ensures that the function returned the same array unchanged.
If you look at the specification for javascript/ecmascript, particularly section 11.9.6, you will see how comparisons with
===
are performed.Since your arrays go all the way down to the seventh step they will have to be the same object, not just two identical objects. The same goes for the regular equality operator (
==
).When you do
[] === []
you're comparing references and not values (or deep comparison by values).Take a look at this solution for javascript array comparison: Comparing two arrays in Javascript