Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why infinite objects dont break the flow in javascript?

This strange phenomenon I've encountered here may have a specific name, which may be why I couldn't find anything about it on Google.

I was working on my project, and I found a strange object in my inspector. My code is broken in many files, and there are many things happening at the same time so I didn't immediately notice, but when I opened my object, I discovered that it was infinite.

I will try to reproduce here what i did:

var monkey = {dad: 1, son: 1, have: null};
var banana = {state: 1, eatable: 1, have: null};

monkey.have = banana;
banana.have = monkey;

console.log(monkey);

If you inspect "monkey" object, and expand the 'have' prop, you will see that it never ends. Because banana always have monkey and monkey always have banana, recursively.

(I think this is probably due to the fact that javascript always passes reference to objects instead of the real value.)

I've seen this in other languages, but it always prevented execution and raised an explicit error.

Why doesn't that happen with javascript? And, more worrying, is this kind of code dangerous in any way?

Thanks for your help!

like image 782
Renato Alves Avatar asked Dec 10 '25 09:12

Renato Alves


1 Answers

Modern browsers' garbage collectors are smart and can detect objects that are only kept alive by a circular reference and dispose of both of them. A lot of languages do this; all the .NET ones, Java, Ruby, Python... it's not so difficult to implement.

like image 63
Ry- Avatar answered Dec 12 '25 21:12

Ry-