How to check if two vars have the same reference?

You use == or === :

var thesame = obj1===obj2;

From the MDN :

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.


The equality and strict equality operators will both tell you if two variables point to the same object.

foo == bar
foo === bar

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.


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.