DEV Community

Jefferson Osagie Iyobosa
Jefferson Osagie Iyobosa

Posted on

Quick question- what happens when you push an array into itself?

So today I was working on something that I had to push a value into an array, but I mistakenly pushed the array itself into itself 🤫🧐🤫. How more confused could that be...

But then the result was stunning as I wondered what I had done wrong.
The script returned an array of arrays which seems to be infinite.

An array inside an array inside an array... continuously.

Just as that was strange, but it was interesting to see what was happening there.

However I still don't understand how that happened. So I'd be glad if anyone can explain or give me a hint what happened.

Top comments (6)

Collapse
 
mrishab profile image
Rishab Manocha

When you pushed an array inside itself, you don't create infinite arrays.

Just like pushing any other object, you have stored a reference (or pointer) to array1 (let's call it "array1") inside the array1 object itself.

When you store other objects, you go from array1 -> items -> item1 which gives you all contents of item1.

Now you go from array1 -> items -> array1 which gives you all the contents of array1. Guess what contents does array1 has? - a reference to array 1.

This is giving you an illusion that you are going down the layers of array infinitely. But instead what is happening is that you are really going in a circle.

Imagine a house with 2 doors. When you enter the house through door1. You see door2 inside the house (your array). When you go through door2, you find yourself standing in front of door 1. You keep entering the same house again and again, creating an illusion that there are infinite houses within your house

Collapse
 
tisaconundrum2 profile image
Nicholas Finch

TLDR: pointers can create cycles.

Collapse
 
tisaconundrum2 profile image
Nicholas Finch

Also you can do stupid shit like this in Linux by creating a symlink of a directory that points to the parent directory causing recursive directories.

Thread Thread
 
frontend_io profile image
Jefferson Osagie Iyobosa

Cool. But why would you want to do that?

Thread Thread
 
tisaconundrum2 profile image
Nicholas Finch

Absolutely no reason to do this. Just a fun discovery.

Collapse
 
frontend_io profile image
Jefferson Osagie Iyobosa • Edited

Wow! Now this makes total sense. Thanks Rishab.
Meanwhile, does this not require some computation power?