tcarpenter tcarpenter - 3 months ago 11
Javascript Question

How Nested JavaScript Loops Naturally Break

I have a question about how nested loops work in JavaScript.

Imagine I have while() loop ... and inside of that is a for() loop. Each has its own separate ending conditions (see below for a schematic).

My question is this: will the while() loop stop the INSTANT its ending condition is met--even if the for() loop within it is not yet finished? Here is an example.

var i = 0;
while (i < somenumber){
for(var j=0; j < othernumber; j++){
somecode();
i++:
}
}


The code seems to be working, but I want to make sure I understand how these structures are supposed to work. The goal is to get the while loop (and thus also the for loop within) to stop the instant that 'i' has reached 'somenumber', even if j has not yet reached 'othernumber'.

Answer

You can use labels and the break command to exit a parent loop directly:

var x = 0, y=0;
b1: {
  while (x++ < 5){
    b2: {
      for(y=0; y < 3; y++){
        if (y === 1){
           x = 2;
           break b1;
         }
       }
    }
  }
}
console.log(`x=${x}  y=${y}`)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break