Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does return stop a loop?

People also ask

Does return stop a for loop Java?

Yes, usually (and in your case) it does break out of the loop and returns from the method.

Does return break loop in C?

There are three basic "flow control" statements in C: return always leaves the currently executed function (optionally with a return value) break leaves the currently executed loop.

Does return in python break loop?

End a while Loop in Python Within a Function Using the return Statement. We can end a while loop in Python within a function using the return statement. In a function, we can also use the return statement instead of the break statement to end a while loop, which will stop the while loop and end the function's execution ...

Can I use return while loop?

The return statement is useful because it saves time and makes the program run faster by returning the output of method without executing unnecessary code and loops. It is good practice to always have a return statement after the for/while loop in case the return statement inside the for/while loop is never executed.


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.


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

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.


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
}