Will two objects/arrays in javascript == each other by coincidence?


Will two objects/arrays in javascript == each other by coincidence?



Lets say I have array a.


var a = [1,2,3];



And then there is array b.


var b = [1,2,3];



Is there ANY possible chance that a == b will return true? Even if it is one in a million. (I know that normally a == b will be false, but I am wondering if there is a chance that it will be true.)


a == b


a == b





No, because if the objects are referencable, they haven't been garbage collected - the objects in memory they reference must be separate.
– CertainPerformance
Jul 2 at 0:39






wondering if there is a chance that it will be true - absolutely zero "chance" - programming languages are not a lottery, they have a defined behaviour, and by definition of the javascript language, in the proposed scenario, a does not equal b
– Jaromanda X
Jul 2 at 0:40



a


b




2 Answers
2



The relevant part of the spec is 11.9.3 The Abstract Equality Comparison Algorithm:



The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:


x == y


x


y


true


false



(Emphasis mine.)



So the answer to your question is no. a == b only returns true if they are in fact the same object.


a == b


true



Is there ANY possible chance that a == b will return true? Even if it is one in a million.



Yes. Instead of just comparing using object/array, you turn both of them to string and compare.




let a = [1,2,3]
let b = [1,2,3]

console.log('array comparison:',a.toString() == b.toString())

let c = { key: 'someVal' }
let d = { key: 'someVal' }

console.log('object comparison:',c.toString() == d.toString())



However, you must understand that they are simply not equal as both array/object are shared by reference, not value!


array/object






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to add background colour in existing image using Swift?

Moria Casán

How to make file upload 'Required' in Contact Form 7?