Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking out of an outer loop from an inner loop in javascript

while(valid){
   for(loop through associative array){
      if(!valid){
         break;
      }
   }
}

I have tried to find a way to break out of the while loop from the if statement. So far, the best method seems to be the goto method that is non-existant in Javascript. What is the best way to cause the if statement to break out of both of the loops it is nested in? Thanks in advance for the help!

like image 251
DitR Avatar asked Jan 13 '23 21:01

DitR


2 Answers

Creating a variable to act as a flag to pass to the outer loop is one way, however, JavaScript provides labels which I think makes the code easier to read as well as reduce the amount of code:

outerloop:
while(valid){
    for(loop through associative array){
      if(!valid){
         break outerloop;
      }
   }
}

Here's some info on labels here Scroll down to the label section. You could even do a continue to the outerloop.

like image 103
user3015682 Avatar answered Feb 01 '23 06:02

user3015682


Depending on what your conditionals are, it should be easy to set the iterator of your for-loop to something that would break it, and set your while condition to false. For example,

while(someBoolean){
    for(var i = 0; i < size; i++){
        if(wantToBreak){
            i = size;
            someBoolean = false;
        }else{
            //Do Stuff
        }
    }
}
like image 31
Jordan Avatar answered Feb 01 '23 08:02

Jordan