Does return stop a loop?

Suppose I have a loop like this:

for (var i = 0; i < SomeArrayOfObject.length; i++) {

  if (SomeArray[i].SomeValue === SomeCondition) {

     var SomeVar = SomeArray[i].SomeProperty;
     return SomeVar;
  }
}

Quick question: does the return stop the execution of the loop in and of itself?


Solution 1:

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.

It is easily verified for yourself:

function returnMe() {
  for (var i = 0; i < 2; i++) {
    if (i === 1) return i;
  }
}

console.log(returnMe());

** Notes: See this other answer about the special case of try/catch/finally and this answer about how forEach loops has its own function scope will not break out of the containing function.

Solution 2:

In most cases (including this one), return will exit immediately. However, if the return is in a try block with an accompanying finally block, the finally always executes and can "override" the return in the try.

function foo() {
    try {
        for (var i = 0; i < 10; i++) {
            if (i % 3 == 0) {
                return i; // This executes once
            }
        }
    } finally {
        return 42; // But this still executes
    }
}

console.log(foo()); // Prints 42