Lapys
Lapys

Reputation: 946

Maximum depth of an Array in JavaScript

So, I was experimented one day when I came across this question in Stack Overflow and got curious: Maximum size of an Array in Javascript (Maximum size of an Array in JavaScript).

Question is, what is the Maximum depth of an Array in JavaScript?

By depth I mean how much can you nest an array within an array until JavaScript gives up?

[1]           // Depth Level: 1
[1, [2]]      // Depth Level: 2
[1, [2, [3]]] // Depth Level: 3
[1, [...]]    // Depth Level: x?

Is it machine-dependent, is it based on the compiler?

No, I'm not sure if there's any practical use for this but it's still something I'm curious about nonetheless.

Upvotes: 5

Views: 1397

Answers (2)

pushkin
pushkin

Reputation: 10217

tadman gave an answer from the runtime perspective (infinite depth), but from a compile-time perspective, there is a limit. It's not one that's built into JavaScript (as far as I know), but consider what the compiler has to do to compile your code.

[1, [2, [3]]]

The compiler needs to turn the above expression into an abstract syntax tree. Roughly:

[ , ]
 /\
1 [ , ]
   /\
  2 [3]

If the compiler runs out of memory when creating those nodes, because there are too many nodes/expressions, then it will crash and your program won't compile. In the case of JavaScript, since it uses a JIT, I guess it's a compilation error that happens at runtime.

Upvotes: 1

tadman
tadman

Reputation: 211610

Generally you can nest different arrays until you run out of memory, but you can nest the same array and get an effectively infinite depth array.

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

x[0][0][0](...)[0]; // Now valid

This shows up as [ [Circular] ] in most debuggers because it's what's called a "circular reference", as in the array contains itself.

This is similar to how you can have self-referential objects:

var x = { };
x.x = x;

// { x: [Circular] }

x.x.x.x.x.x.x.x.x(...).x; // Now valid

JavaScript itself doesn't really care what depth something is, the language has no intrinsic limit. Sometimes circular references are a feature, like x.y refers to something that refers back to x for convenience, a way of showing mutual association. That's technically infinite depth, but it's unlikely you'd use it that way.

Here's a simple example of that phenomenon:

var x = { };
var y = { };

x.y = y;
y.x = x;

x.y.x.y.x.y; // Pointless, but valid.

Upvotes: 3

Related Questions