Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test same object instance in Javascript?

Say I have the following objects in Javascript:

var a = { xxx: 33 }; var b = { xxx: 33 }; var c;  c = a; 

What is the Javascript test that will tell me whether I am dealing with the same object instance? In other words, it should return false for a and b, b and c, but true for a and c.

like image 511
Jérôme Verstrynge Avatar asked Oct 06 '14 11:10

Jérôme Verstrynge


People also ask

How do you check if something is the same in JavaScript?

If you are after checking whether 2 objects are the same, a double equal == is enough. However, for value types (primitives), you may be in a for surprise. Check out the following: var a = 1; // Integer 1 var b = '1' // String '1' if (a == b) console.

How do you check if two objects have the same values?

equals() versus == The == operator compares whether two object references point to the same object. For example: System.

How can we compare two objects in JavaScript?

Objects are not like arrays or strings. So simply comparing by using "===" or "==" is not possible. Here to compare we have to first stringify the object and then using equality operators it is possible to compare the objects.


2 Answers

You just need this

if(c == a) {    // same instance } 

a == b and b == c will return false

like image 63
Amit Joki Avatar answered Sep 23 '22 06:09

Amit Joki


Just a standard equality test:

( a == c ) // true ( a == b ) // false 
like image 45
Quentin Avatar answered Sep 20 '22 06:09

Quentin