Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a limit to how many levels you can nest in JavaScript?

Say you have this really complex algorithm that requires dozens of for loops.

Does JavaScript have a limit to how deep loops can be nested or is there no limit?

What is the best practice for deep nested for loops?

I tried searching on MDN but couldn't find what I was looking for

Edit

I'm looking if there is a built in limit. For example if you had something like this

If ( a = 1, a < 3, a++) {
    if (b = 1; b < 3; b++) {
        ...
        if (cd = 1; cd < 3; cd++) 

Would this actually be possible or would JS throw an error

Edit: Here's a theoretical example of when you might need this

You want to find if any 500 numbers in an array sum up to equal another number. You'd need about 500 loops to add the numbers to a combos array and then filter them to find the sum of them relative to a third number.

Would there even be enough space in the universe to store that much data?

like image 913
user5680735 Avatar asked Nov 23 '25 07:11

user5680735


1 Answers

There's no limit in the specification. There will probably be a limit in any implementation due to memory/stack overflows...

For example, this works fine:

var s = 0;
var is = new Array(11);

for(is[0] = 0; is[0] < 2; is[0]++) {
  for(is[1] = 0; is[1] < 2; is[1]++) {
    for(is[2] = 0; is[2] < 2; is[2]++) {
      for(is[3] = 0; is[3] < 2; is[3]++) {
        for(is[4] = 0; is[4] < 2; is[4]++) {
          for(is[5] = 0; is[5] < 2; is[5]++) {
            for(is[6] = 0; is[6] < 2; is[6]++) {
              for(is[7] = 0; is[7] < 2; is[7]++) {
                for(is[8] = 0; is[8] < 2; is[8]++) {
                  for(is[9] = 0; is[9] < 2; is[9]++) {
                    for(is[10] = 0; is[10] < 2; is[10]++) {
                      s++;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

document.write(s);
like image 96
Amit Avatar answered Nov 24 '25 21:11

Amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!