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?
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 < 5; 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 the forEach
callback has its own function scope, so it will not break out of the containing function.