Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 442
frenchie Avatar asked May 06 '12 14:05

frenchie


People also ask

How do you exit a for loop in JavaScript?

The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).

Does return exit a for loop?

Yes, return stops execution and exits the function. return always** exits its function immediately, with no further execution if it's inside a for loop.

How do you abort a for loop?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.

How do you exit JavaScript?

Sometimes when you're in the middle of a function, you want a quick way to exit. You can do it using the return keyword. Whenever JavaScript sees the return keyword, it immediately exits the function and any variable (or value) you pass after return will be returned back as a result.


1 Answers

You're looking for the break statement.

like image 188
SLaks Avatar answered Sep 28 '22 11:09

SLaks