Search code examples
javascriptjsonbrowser-console

Object Properties in Browser's Console


Whenever i log any javascript object into browser, I am keen to explore it by expanding what is inside in the console window, As one such example is

console.log(console);

I sure found what is inside, But the real query starts now, When i expand the object it has a property called __proto__ with its sub-properties inside, then again this has a property of contructor and the cycle goes on as it has __proto__ and again and so on.

Does it end ?

If Yes, what does this multiple repetition denotes ?

If No, Why doesn't browser hangs on printing such infinite object ?

  • Any Leads highly appreciated

Thanks & Regards Shohil Sethia


Solution

  • If Yes, what does this multiple repetition denotes ?

    Derek has already given you a link explaining prototype chain.

    If No, Why doesn't browser hangs on printing such infinite object ?

    __proto__ is a special property and will be handled in special way. Instead lets take a generic example:

    var a = {
      nest : function() {
        this.b = this; 
      }
    }
    
    a.nest();

    This will create an object a that has a property b that points to the main object a itself.

    If you do console.log(a) you will see the similar behavior as you saw in case of __proto__. You can go on expanding property b N number of times and it will always show an object that has a property b and a method nest.

    In this case browser doesn't hang because it iterates on only one level of properties. When you try to expand property b it will again iterate on only 1 level of sub-properties. It never iterates on nested properties and hence doesn't face any issue. On the other hand if you try to use JSON.stringify(a) it will give an error about circular reference because to generate string from the object it has to iterate on all nested properties.