javascript exiting for loop without returning

I have a for loop that I want to exit like this:

function MyFunction() {
  for (var i = 0; i < SomeCondition; i++) {
     if (i === SomeOtherCondition) {
        // Do some work here.
        return false;
     }
  }
  // Execute the following code after breaking out of the for loop above.
  SomeOtherFunction();
}

The problem is that after the // Do some work here. statements executes, I want to exit the for loop but still want to execute the code below the whole for loop (everything below // Execute the following code after breaking out of the for loop above.).

The return false statement does exit the for loop but it also exits the whole function. How do I fix this?


Solution 1:

You're looking for the break statement.

Solution 2:

Either use a break or continue statement

function MyFunction() { 
  for (var i = 0; i < SomeCondition; i++) { 

     if (i === SomeOtherCondition) { 

        // Do some work here 
        break;
     } 
  } 

  SomeOtherFunction(); 
  SomeOtherFunction2(); 
} 

Or to continue processing items except for those in a condition

function MyFunction() { 
  for (var i = 0; i < SomeCondition; i++) { 

     if (i != SomeOtherCondition) continue;

     // Do some work here 
  } 

  SomeOtherFunction(); 
  SomeOtherFunction2(); 
} 

Solution 3:

Several people have offered break as the solution, and it is indeed the best answer to the question.

However, just for completeness, I feel I should also add that the question could be answered while retaining the return statement, by wrapping the contents of the if() condition in a closure function:

function MyFunction() {

  for (var i = 0; i < SomeCondition; i++) {

     if (i === SomeOtherCondition) {
        function() {
           // Do some work here
           return false;
        }();
     }
  }

  SomeOtherFunction();
  SomeOtherFunction2();
}

As I say, break is probably a better solution in this case, as it's the direct answer to the question and the closure does introduce some additional factors (such as changing the value of this, limiting the scope of variables introduced inside the function, etc). But it's worth offering as a solution, because it's a valuable technique to learn, if not necessarily to be used in this particular occasion then certainly for the future.

Solution 4:

Break - breaks the whole loop. Continue - skips a step in a loop. So it skips the code below continue;

Solution 5:

Would setting the i variable to the somecondition value be a good way?

for (var i=0; i<SomeCondition; i++) {

   if (data[i]===true) {
   //do stuff
   i=SomeCondition;
   }
}