javascriptloopsreferenceinfinity

Are there any issues with infinity references in javascript (example)


Are there any performance issues or things to be wary of when things reference each other in such a way that they can be accessed infinitely?

Here's an example...

var Foo = function () { 
    var self = this; 

    this.setBar = function (bar) {
        self.bar = bar;
        self.bar.foo = self;
    }
};

var Bar = function () {};

var foo = new Foo();
var bar = new Bar();
foo.setBar(bar);

// infinite references!
console.log(foo.bar.foo.bar.foo); 

Solution

  • Some issues to be aware of:

    1. You can't call JSON.stringify() on an object that has circular references. In fact, the JSON format itself makes no allowances for specifying a circular reference.
    2. You can't call any function that internally relies on JSON.stringify() in order to serialize data and/or send the flattened object over the wire.
    3. Only really smart code (that detects and does the right thing with circular references) can recursively iterate something with a circular reference. It's fairly easy to create an infinite loop with a relatively simple looking recursive iterator if your data has circular references in it. Recursive iteration code can also be protected from circular references, but it's easier to do it transparently with the ES6 Set or Map object than it is in ES5.

    As long as you don't get caught in one of these circular iterations or have a need to represent your data structure in JSON, there's nothing particularly wrong with it - sometimes it is just the expedient way to do things.

    The browser itself has many examples of such circular references. For example, the entire DOM has this as parent points to child and child points to parent.

     node.firstChild.parentNode.firstChild.parentNode.firstChild.parentNode === node