How to check if two vars have the same reference?
JavascriptEqualityJavascript Problem Overview
How can you check if two or more objects/vars have the same reference?
Javascript Solutions
Solution 1 - Javascript
You use ==
or ===
:
var thesame = obj1===obj2;
> If both operands are objects, then JavaScript compares internal > references which are equal when operands refer to the same object in > memory.
Solution 2 - Javascript
The equality and strict equality operators will both tell you if two variables point to the same object.
foo == bar
foo === bar
Solution 3 - Javascript
For reference type like objects, == or === operators check its reference only.
e.g
let a= { text:'my text', val:'my val'}
let b= { text:'my text', val:'my val'}
here a==b will be false as reference of both variables are different though their content are same.
but if I change it to
a=b
and if i check now a==b then it will be true , since reference of both variable are same now.
Solution 4 - Javascript
As from ES2015
, a new method Object.is()
has been introduced that can be used to compare and evaluate the sameness of two variables / references:
Below are a few examples:
Object.is('abc', 'abc'); // true
Object.is(window, window); // true
Object.is({}, {}); // false
const foo = { p: 1 };
const bar = { p: 1 };
const baz = foo;
Object.is(foo, bar); // false
Object.is(foo, baz); // true
Demo:
console.log(Object.is('abc', 'abc'));
console.log(Object.is(window, window));
console.log(Object.is({}, {}));
const foo = { p: 1 };
const bar = { p: 1 };
const baz = foo;
console.log(Object.is(foo, bar));
console.log(Object.is(foo, baz));
Note: This algorithm differs from the Strict Equality Comparison Algorithm in its treatment of signed zeroes and NaNs.
Solution 5 - Javascript
Possible algorithm:
Object.prototype.equals = function(x)
{
var p;
for(p in this) {
if(typeof(x[p])=='undefined') {return false;}
}
for(p in this) {
if (this[p]) {
switch(typeof(this[p])) {
case 'object':
if (!this[p].equals(x[p])) { return false; } break;
case 'function':
if (typeof(x[p])=='undefined' ||
(p != 'equals' && this[p].toString() != x[p].toString()))
return false;
break;
default:
if (this[p] != x[p]) { return false; }
}
} else {
if (x[p])
return false;
}
}
for(p in x) {
if(typeof(this[p])=='undefined') {return false;}
}
return true;
}