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

Asked

Viewed 11,353 times

12

Let’s say I have this loop for 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 him making use of the break.

This is the right way to stop one loop?

2 answers

13


If you’re talking about a cycle for:

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

If you’re talking about a cycle forEach (native from ES5) there is no stopping the cycle forEach. One solution is to have the cycle within a function and call return, then yes leaving the loop, another solution is to call throw BreakException within a try/catch. Can be good in terms of optimization.

  • 3

    Thanks for the supplement on the cycle forEach.

7

Yes. If you want to go out of a loop, be it a for or any other, you use the break.

In your code, you will log only "Name 2", then "Stop", and your loop to. I recommend that you do 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;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.