3

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?

user5680735
  • 703
  • 2
  • 7
  • 21
  • You will need to be more specific about the function. – marblewraith Feb 05 '16 at 07:20
  • you can try recursive function – Anshuk Feb 05 '16 at 07:22
  • 1
    You'd run into stack overflow issues. The spec doesn't impose a limit, browsers do. But then there's things like `tail-call optimization` and `trampolining` which are techniques to help reduce the stack size among other things. Which means you can have much higher levels of recursion if you really wanted too. EDIT: This explains it well http://stackoverflow.com/questions/25228871/how-to-understand-trampoline-in-javascript#answer-27704484 – ste2425 Feb 05 '16 at 07:45
  • "Would there even be enough space in the universe to store that much data?" Yes. 500 numbers in an array? Then work out all the permutations? That is 500^2=250k. **Yes, there is _at least_ 250k of space in the universe** – Tersosauros Feb 08 '16 at 01:47

3 Answers3

4

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);
Amit
  • 45,440
  • 9
  • 78
  • 110
1

Just to kick in with a short test that I've since modified to not count loops as much as see the memory limit... This code (please don't use it, your machine will hate you):

    function x () {
    function newLoop (index) {
        var y = [];
        console.log("index");
        for (i = index; i < index+1000; i++) {
            y.push(i);
            if(i == index+999) {
                console.log(i);
                newLoop(i);
            }
        }
    }
    newLoop(0);
}
x();

has stopped at logging 499500 to the console. That is probably hitting some safety switch or the memory limit.

That's 500 nested loops.

In an earlier test with a lighter version of this code I've gotten up to 999 nested loops in just the first second, with the code clogging up my browser for another few seconds (but not displaying the rest because of "too many messages per second to the console" error).

I didn't care enough too bother with more details after that nor do I see benefits of a more detailed description here, but (in my project) I'm traversing HTML with a whole lot of nested loops in badly laid out pages and these results faaar exceed my needs.

TL;DR: memory plays a bigger role than the number of loops, but I've gotten above a 1000 nested loops. Please don't ever use that many though :)

PS. this was run in Edge, for the version check the date of my post :)

Amit K Bist
  • 6,760
  • 1
  • 11
  • 26
  • Its stopped at around 140k, on my reasonably modern laptop (huawei matebook 2020). Visual studio compiled c++ nesting level is around 100, which seems reasonable. – Ali Mert Çakar May 13 '21 at 19:35
0

There is no maximum nesting level that you should worry about when you are writing code that a human is supposed to read and maintain. You can nest hundreds of loops without problems.

However, you should avoid it wherever possible! At some point someone will have to understand your code (most likely it's you, when you are debugging!) and will curse you. It should be possible to extract inner loops into a separate function with a meaningful name.

lex82
  • 11,173
  • 2
  • 44
  • 69