Search code examples
javascriptarraysjavascript-objects

How many nested Objects or Arrays are possible in Javascript?


This question comes out of curiosity, but is there a limit to how many nested Objects a given Object can have (or similarly, since typeof [] === "object", how many Arrays can be nested in an Array) in JS?

I thought about creating an array that could have thousands of nested arrays, with thousands of numbers inside them as well. Setting aside possible best practice issues, I was wondering whether I could run into a cap at some point (that is, supposing it's not just a problem with, e.g., too much recursion or nested for-loops, or hardware limitations).

Related: how many nested object should i define in javascript?


Solution

  • When you create an object or array in Javascript, it allocates a small block of memory to store the value. All values in the object or array, including other objects or arrays, are allocated their own separate block of memory, with a reference to the address in the parent object or array.

    Therefore, how many nested objects or arrays (or how many objects or arrays, period) that you can have initialized in a script at one time, is entirely dependent on how much RAM your computer has. Once you start to reach the limits of your RAM capacity, processor speed comes into play, as the faster your computer can locate, create, and reallocate address space, the longer the system can run before it crashes.