Search code examples
javascriptarraysgoogle-chrome-console

infinite inner arrays with push() method in javascript chrome console


Recently i was experimenting with array push() method in javascript. I created an array, and pushed the same array using push method.

var a=['hello', 4]

a.push(a)

the result was surprising, when i explored the array items in chrome console, there was infinite array produced. i want to know why this is happening. As the push() method adds the element on last.

I was expecting this result

['hello, 4, ['hello',4]]

but the result was something else, here is the screenshot of chrome console problem screenshot, infinite inner arrays using push method in JavaScript


Solution

  • When you assign an object to a variable in Javascript (and indeed in most similar languages), that variable holds what is called a "reference" to that object. Note that arrays in JS are objects, but primitive values like strings and numbers are not.

    One consequence of object assignments being "by reference" is that any change you make to that object - even if its done to another variable that happens to reference the same object - will "show up" when you inspect the original variable.

    So here, you start off with

    var a=['hello', 4]
    

    And then do

    a.push(a)
    

    then the object (array) to which a points has been changed. It now has an additional element on the end - which is a, the very same array we're talking about.

    So it expands recursively:

    a = ['hello', 4, a]
      = ['hello', 4, ['hello', 4, a]]
      = ['hello', 4, ['hello', 4, ['hello', 4, a]]]
       ...
    

    And so on, infinitely. This doesn't require an infinite amount of memory, because the third element of the array is simply a reference to the memory location which holds the array.