1

I wanted to know what happens if I push the value of an array inside the same array. I did it and there were no errors nor any problems. It just returned an array which has the same array inside that and so on...

I understand that array is passed through references but the pointer to the array still must take some memory.

So how deep does it go? And how do browsers handle this if they need to do it at all?

let arr = [1, 2, 3];
arr.push(arr);
trincot
  • 317,000
  • 35
  • 244
  • 286
anantdd
  • 125
  • 7
  • `I understand that array is passed through references` `So how deep does it go?` This question implies you do not fully understand. – Patrick Roberts May 07 '19 at 05:51
  • The duplicate explains this with an object but the idea is same. "*how deep does it go*" try: `arr[3][3][3][3][3][3][3][3]` – adiga May 07 '19 at 06:02

1 Answers1

1

Arrays are objects in JS, and objects are passed by references.

If you create an object, and set a property to a reference to that object, it will be infinite.

Your browser won't crash since the object stored only once, and every level loads the same object, so this won't occupy too much space.

The following equality will be true:

arr[3] === (arr[3])[3]

So arr[3][3] will be interpreted like:

Load arr                 (arr)[3][3]
Load arr[3] => Load arr  (arr[3])[3]
Load arr[3] => Load arr  (arr[3])
Output: arr              (arr)
FZs
  • 16,581
  • 13
  • 41
  • 50