Skip to content Skip to sidebar Skip to footer

In A Nested-loop Js Function, Does 'return' Exit The Loop, Or The Whole Function?

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, an

Solution 1:

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.

Solution 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:

functionfoo() {
    for(var i = 0; i < 5; i++) {
        var bar = function() {
            // whateverreturn;
        }
        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?

Solution 3:

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.

Post a Comment for "In A Nested-loop Js Function, Does 'return' Exit The Loop, Or The Whole Function?"