Course contentsShow
← JavaScript
Lesson 377 of 2,72310. LoopsFree lesson

Early Exit and Short-Circuiting

Using break, continue, or return strategically to skip unnecessary iterations and improve efficiency.

Early Exit and Short-Circuiting

You'll learn how to skip unnecessary loop iterations by exiting or continuing strategically, making your code faster and more efficient.

When you're searching through data or processing items in a loop, you don't always need to check every single element. Sometimes you can stop early once you've found what you need, or skip iterations that don't matter. This is called early exit and short-circuiting.

The Core Idea

Think of it like searching for your keys in your house. Once you find them in the kitchen, you don't keep searching the bedroom and living room—you stop immediately. The same logic applies to loops.

Using break for early exit: When you find what you're looking for or meet a condition that makes further iteration pointless, use break to exit the loop entirely.

Using continue to skip work: When a particular iteration doesn't need processing, use continue to skip to the next one without executing the remaining code in the loop body.

Using return in functions: If your loop is inside a function, return immediately exits both the loop and the function, which is even more efficient when you have a result.

Why This Matters for Performance

Every iteration costs time. If your loop runs 10,000 times but you find your answer on iteration 50, why continue the remaining 9,950 times? Strategic use of break, continue, or return prevents wasted CPU cycles. You've minimized work inside the loop body—now minimize how many times the body runs.

Key Takeaway: Exit loops as soon as you've accomplished your goal using break, return, or skip unnecessary work with continue to make your code run faster and more efficiently.