Object identification in JavaScript

How can I check if two variables point to the same object? This means that if I mutate it, the value pointed to by both variables changes. Python has an operator is

, what about JavaScript?

+3


source to share


2 answers


the strict equality operator ( ===

) will evaluate to true if the references are the same without converting to any type:

var a, b, c;
a = {};
b = {};
c = a;
console.log( a === b ); //false
console.log( a === c ); //true

      




After shooting two posts that committed the same mistakes, I must point out that ==

it is possible to equate a reference type with a value type due to type conversion:

var a, b;
a = {
    toString: function () {
        return 'foo';
    }
};
b = 'foo';
console.log( a == b ); //true
console.log( a === b ); //false

      

AFAIK, if you can guarantee that both variables are reference types, it ==

should work fine, but it's rarely the case that you're better off not sticking to a strict comparison most of the time.

+8


source


The Javascript equivalent operator is "===".



Likewise, "! ==" is the same as "is not" in Python.

+2


source







All Articles