246

If I have the following for loop


    for (var i = 0; i < SomeArrayOfObject.length; i++) {
    
      if (SomeArray[i].SomeValue === SomeCondition) {

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

Does the return statement stop the function's execution?

JΛYDΞV
  • 8,532
  • 3
  • 51
  • 77
frenchie
  • 51,731
  • 109
  • 304
  • 510

7 Answers7

325

Yes, functions always end whenever their control flow meets a return statement.

The following example demonstrates how return statements end a function’s execution.

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 trycatchfinally and this answer about how the forEach callback has its own function scope, so it will not break out of the containing function.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • 53
    > return always exits its function immediately, with no further execution if it's inside a loop [...unless it's a forEach loop](http://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function/34653650) – o-o Jun 27 '16 at 10:50
  • 14
    @o-o Sort of true. `return` still returns from the current iteration of the function callback, in its own scope, but would not be expected to break from the entire calling method `forEach()`. So it isn't returning from the _loop itself_, but it is returning from the callback the loop executes. In the code example from the linked question, the output is `1,2,4,5` skipping the `3` because of the return. – Michael Berkowski Jun 27 '16 at 11:33
  • 1
    Maybe the red thread is that `return`will always return from the current `this` context. – o-o Jun 27 '16 at 16:06
  • 1
    The alternative to using forEach() or for() on an array for “potentially” early loop termination is using some(). – Anjan Biswas Jul 04 '18 at 02:28
  • 2
    I know this is trivial for some people, but this is so good know because you no longer have to `break` and then `return`. – NoName Oct 17 '19 at 22:12
  • 1
    `forEach` isn't a loop - it's a Array method with a pretty clear definition, so it's not really an exception to the `return exits a loop` rule – Drenai May 08 '22 at 10:18
86

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
John Girata
  • 2,021
  • 15
  • 15
23

This code will exit the loop after the first iteration in a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
  if (iterator.name == 2) {
    return;
  }
  console.log(iterator.name);// 1
}

the below code will jump on the condition and continue on a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];

for (const iterator of objc) {
  if (iterator.name == 2) {
    continue;
  }
  console.log(iterator.name); // 1  , 3
}
PersianIronwood
  • 639
  • 8
  • 19
  • Thanks, this help me a lot, i'm using node and the return is breaking my for, for each and for...of, the continue works like i expected – veroneseComS Jan 28 '20 at 11:24
16

The return statement stops a loop only if it's inside the function (i.e. it terminates both the loop and the function). Otherwise, you will get this error:

Uncaught SyntaxError: Illegal return statement(…)

To terminate a loop you should use break.

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
5

Yes, once the return statement is executed, the entire function is exited at that very point.

Just imagine what would happen if it did not and continued looping, and executing that return statement each time? It would invalidate it's meaning of returning a value when you think about it.

Keldon Alleyne
  • 2,103
  • 16
  • 23
1

The answer is yes, if you write return statement the controls goes back to to the caller method immediately. With an exception of finally block, which gets executed after the return statement.

and finally can also override the value you have returned, if you return inside of finally block. LINK: Try-catch-finally-return clarification

Return Statement definition as per:

Java Docs:

a return statement can be used to branch out of a control flow block and exit the method

MSDN Documentation:

The return statement terminates the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call.

Wikipedia:

A return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called, known as its return address. The return address is saved, usually on the process's call stack, as part of the operation of making the subroutine call. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.

user1179299
  • 326
  • 1
  • 4
  • 16
-1

"return" does exit the function but if you want to return large sums of data, you can store it in an array and then return it instead of trying to returning each piece of data 1 by 1 in the loop.