What is the correct way to stop a "for" loop?

9

Let's say I have this for loop that works based on my array name:

var nomes = ["Nome 1", "Nome 2", "Nome 3"];

for(i = 0; i <= 2; i++) {
   if(nomes[i] == "Nome 2") {
     console.log(nomes[i]);
     console.log("Stop!");
     break;
   }
}

I'm stopping it by making use of break .

Is this a good way to stop a loop ?

    
asked by anonymous 12.05.2015 / 19:41

2 answers

11

If you're talking about a for cycle:

  • The right method to stop execution and do no more iteration is break .
  • The method to skip an iteration, not running more code from this iteration, but running the following is continue , saving processing resources.

If you are talking about a forEach cycle (native from ES5) there is no way to stop the forEach cycle. One solution is to have the cycle inside a function and call return , then out of the loop, another solution is to call throw BreakException within a try / catch . It may be good in terms of optimization.

    
12.05.2015 / 19:53
7

Yes. If you want to exit a loop, be it a for or any other, you use break .

In your code, you will log in only "Name 2", then "Stop", and your loop to. I recommend that you make the console.log() of your counter out of condition for you to analyze the behavior. In this case, the code is:

var nomes = ["Nome 1", "Nome 2", "Nome 3"];

for(i = 0; i <= 2; i++) {
    console.log(i);
    if(nomes[i] == "Nome 2") {
        console.log(nomes[i]);
        console.log("Stop!");
        break;
    }
}
    
12.05.2015 / 19:47