0
0
Javascriptprogramming~10 mins

Return inside loops in Javascript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Return inside loops
Start function
Enter loop
Check condition
Yes
Return value?
YesExit function immediately
No
Continue loop
Loop ends
Return after loop or undefined
The function starts and enters a loop. If a return is hit inside the loop, the function exits immediately. Otherwise, the loop continues until done.
Execution Sample
Javascript
function findFirstEven(arr) {
  for (let num of arr) {
    if (num % 2 === 0) return num;
  }
  return null;
}
This function returns the first even number found in the array or null if none.
Execution Table
StepnumCondition (num % 2 === 0)ActionReturn ValueFunction Exit
13falseContinue loopnoneNo
27falseContinue loopnoneNo
34trueReturn 44Yes
💡 Function exits immediately when return is executed at step 3.
Variable Tracker
VariableStartAfter 1After 2After 3Final
numundefined3744
Key Moments - 2 Insights
Why does the function stop running when it hits return inside the loop?
Because return immediately exits the entire function, not just the loop. See execution_table step 3 where return 4 ends the function.
What happens if no number satisfies the condition inside the loop?
The loop finishes all iterations without returning, then the function returns null after the loop, as shown by the absence of return in steps 1 and 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'num' when the function returns?
A4
B3
C7
Dnull
💡 Hint
Check the 'num' column at the step where 'Return Value' is set.
At which step does the function exit due to return inside the loop?
AStep 1
BStep 2
CStep 3
DAfter loop ends
💡 Hint
Look at the 'Function Exit' column in the execution table.
If the array was [1,3,5], what would the function return?
A1
Bnull
C5
Dundefined
💡 Hint
No number satisfies the condition, so the function returns after the loop.
Concept Snapshot
Return inside loops:
- A return inside a loop exits the entire function immediately.
- The loop stops running once return is hit.
- If no return in loop, function continues after loop.
- Useful to find and return first matching item quickly.
Full Transcript
This example shows how a return statement inside a loop causes the function to exit immediately when the condition is met. The function findFirstEven loops through numbers, and returns the first even number it finds. If no even number is found, it returns null after the loop. The execution table traces each step, showing variable values and when the function exits. This helps beginners understand that return inside loops stops the whole function, not just the loop.