frenchie frenchie - 3 months ago 8
Javascript Question

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?

Answer

Yes, return stops execution and exits the function. return always exits its function immediately, with no further execution if it's inside a loop.

It is easily verified for yourself:

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

alert(returnMe());
// 1

Note: See this other answer about the special case of try/catch/finally.

Comments