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?
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).
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.
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.
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.
You're looking for the break
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With