In A Nested-loop Js Function, Does 'return' Exit The Loop, Or The Whole Function?
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?"