Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a JavaScript variable is a reference to another variable

Tags:

javascript

If I make an object, and then set another variable equal to that object, it's just a pointer to the original object. Is there a way to tell if a variable is just a reference, and if so, determine the original variable name?

E.g if I want to json encode an object that has a property that references back to the original object, it creates an infinite loop. I'd like to test if a property is a reference and if so just mark it as such, without rewriting the same object.

like image 646
juacala Avatar asked Dec 11 '25 21:12

juacala


1 Answers

var foo = {'some': 'object'};
var bar = foo;

After this, foo and bar are exactly the same as in "they both point to the same object". But besides that there is no relationship between foo and bar, so bar is not a reference to foo but to the same object. So the answer is "no" since JavaScript does not have references to other variables.

However, to check for circular dependencies - which is what you actually need/want in your example - there are various other, more appropriate, solutions available this question: Is there a way to test circular reference in JavaScript?

Additionally, native JSON encoding using JSON.stringify() already checks for this:

>>> var obj = {};
>>> obj.x = obj;
>>> JSON.stringify(foo)
TypeError: cyclic object value
like image 119
ThiefMaster Avatar answered Dec 13 '25 10:12

ThiefMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!