javascript exiting for loop without returning
You're looking for the break
statement.
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();
}
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.