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

twitter logo github logo ・1 min read

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.

twitter logo DISCUSS (7)
markdown guide
 

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

 
 

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.

 

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

 

You might find this interesting:

const a = {};
a.a = a;

// What does `a` look like now?   
Classic DEV Post from Sep 25 '18

Teaching the "right" mindset to junior devs in a team

Junior developers, especially those that is fresh out of college, can be challenging to manage. In my short experience as an engineering/team manager, I'd like to learn the best practices that the community has experienced. Junior developers, we want to listen to your plights as well.

Jefferson Osagie Iyobosa profile image
Passionate front-end developer looking forward to learning more