When you use the animals.push(animals)
method, you are essentially pushing the array itself into the array. This results in a single array that keeps growing in size, with each new element being a reference to the original array. This leads to a nested structure like this:
['pigs', 'goats', 'sheep',
['pigs', 'goats', 'sheep',
['pigs', 'goats', 'sheep',
['pigs', 'goats', 'sheep',
...
]
]
]
]
Contrary to popular belief, this does not consume infinite memory, as it is all contained within one array. You can think of it as:
animals (ref)
│
│ ┌───────────────────────────────┐
v v │
┌──────────┬──────────┬──────────┬───│───────┐
│ "pigs" │ "goats" │ "sheep" │ (ref) │
└──────────┴──────────┴──────────┴───────────┘
If you wish to avoid this recursive behavior and just push ['pigs', 'goats', 'sheep']
without affecting the original array, you should create a new array with those values:
animals.push([...animals])
Now, your structure will look like this:
['pigs', 'goats', 'sheep', ['pigs', 'goats', 'sheep']]
Visualizing this arrangement:
animals (ref)
│
│
v
┌──────────┬──────────┬──────────┬───────────┐
│ "pigs" │ "goats" │ "sheep" │ (ref) │
└──────────┴──────────┴──────────┴───│───────┘
┌──────────────────────────────────┘
v
┌──────────┬──────────┬──────────┐
│ "pigs" │ "goats" │ "sheep" │
└──────────┴──────────┴──────────┘
As depicted, the nested array is now a separate array with 3 entries instead of 4.