-1

I have a piece of JavaScript I can't get to work (Euler Project, problem 3), and I have nested loops as part of the solution. If a condition is met, I want to exit a child loop, and continue with the parent loop. Should I be using return or break to accomplish this?

I've read the answers here: Best way to break from nested loops in Javascript? but am still confused, especially on the answer that includes an anonymous function as part of the solution.

Community
  • 1
  • 1
awesame
  • 84
  • 2
  • 13

3 Answers3

6

return always exits the current function.

If you need to exit a loop you should be using break which terminates the current loop, label or switch statement.

tkone
  • 22,092
  • 5
  • 54
  • 78
2

break exits the loop, and return exits the function, BUT... in javascript you can freely nest them, so you can have a function in a loop in a function in a loop etc. In this case, return terminates its nearest function and not the outer one. Example:

function foo() {
    for(var i = 0; i < 5; i++) {
        var bar = function() {
            // whatever
            return;
        }
        bar();
        // after 'bar' returns, we're here and the loop goes on
    }
}

PS I'm wondering why you need nested loops for Euler3... could you post your code?

georg
  • 211,518
  • 52
  • 313
  • 390
1

To exit a loop use always the keyword break, unless you determine something inside the loop that makes you decide to exit the whole function, and in that case you use return keyword.

The link you posted, about an anonymous function is ingenious, that solution has 3 loops, but depending on a condition the programmer wants to exit the 2 inner loops simultaneously, but not the outer most, so he wrapped the 2 inner loops inside an anonymous function that executes for each iteration of the outer loop, so that when he decides to break the 2 inner loops, he can call return without exiting the outer most.

Regards.

João Pinho
  • 3,725
  • 1
  • 19
  • 29