T. Rexman
T. Rexman

Reputation: 73

in javascript, what happens if: x = []; x.push(x);?

var x = []; 
x.push(x);

x now seems to be an infinitely deep russian-doll type meta array.

if you check x[0][0][0].... as many [0] indexes as you add, it still returns a one-item array.

but is there a finite depth cutoff? or are new levels procedurally generated when you check? those are the only two possibilities I can think of.

Upvotes: 5

Views: 230

Answers (3)

Ballbin
Ballbin

Reputation: 727

There is no loop here. You are creating an empty array and setting it into x. Then the next line x.push(x); is just pushing an empty array in to x. If you where to add do x.push(x); again it would push an array into x that has an empty array in the first index.

Upvotes: 0

Toni
Toni

Reputation: 283

Nothing is generated when you get the x at any level. The x is inserted as a reference.

When dereferencing x[0], you get x.

x == x[0];

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83366

var x = []; 
x.push(x);

x now seems to be an infinitely deep russian-doll type meta array.

Not really. x is an array. The first element in the array points to the same memory location as x itself. Nothing more, nothing less.

But yes, you can do

x[0][0][0]

as many times as you like, since you're just re-referencing the same memory location over and over again.

Upvotes: 3

Related Questions