When to Use break vs return in Loops
You'll learn how to choose between break and return based on whether you need to exit just the loop or the entire function.
The Core Difference
Both break and return stop loop execution, but they work at different levels:
breakexits only the loop it's in, then continues with the next line of code after the loopreturnexits the entire function immediately, sending a value back to the caller
Think of it like leaving a building: break is stepping out of one room into the hallway, while return is exiting the entire building.
When to Use break
Use break when you've found what you need in the loop but still have more work to do in the function:
function processData(items) {
let found = null;
for (let i = 0; i < items.length; i++) {
if (items[i] > 100) {
found = items[i];
break; // Exit loop only
}
}
// More code runs here after the loop
console.log('Search complete');
return found;
}
When to Use return
Use return when finding something means you're completely done with the function:
function findFirst(items) {
for (let i = 0; i < items.length; i++) {
if (items[i] > 100) {
return items[i]; // Exit function immediately
}
}
return null; // Only if nothing found
}
Key Takeaway: Use break to exit a loop and continue the function; use return to exit both the loop and the function in one step. Choose based on whether you have more logic to execute after the loop.