break and continue
break and continue
Section titled “break and continue”Introduction
Section titled “Introduction”break exits a loop entirely. continue skips the current iteration and moves to the next one.
Visual Explanation
Section titled “Visual Explanation”flowchart TD Loop["for (i=0; i<10; i++)"] Break{"i === 5?"} BreakYes["break — exit loop"] Continue{"i === 3?"} ContinueYes["continue — skip iteration"] Body["console.log(i)"] End["Loop ends"]
Loop --> Break Break -->|Yes| BreakYes BreakYes --> End Break -->|No| Continue Continue -->|Yes| ContinueYes ContinueYes --> Loop Continue -->|No| Body Body --> Loopfor (let i = 0; i < 10; i++) { if (i === 5) break; console.log(i); // 0, 1, 2, 3, 4}// Loop stops when i reaches 5continue
Section titled “continue”for (let i = 0; i < 5; i++) { if (i === 2) continue; console.log(i); // 0, 1, 3, 4}// Skips i = 2Use Cases
Section titled “Use Cases”// break — finding an elementconst numbers = [1, 2, 3, 4, 5];let found = null;for (const n of numbers) { if (n === 3) { found = n; break; // stop searching }}
// continue — filtering in a loopfor (let i = 0; i < 10; i++) { if (i % 2 === 0) continue; // skip evens console.log(i); // 1, 3, 5, 7, 9}Summary
Section titled “Summary”breakexits the loop immediatelycontinueskips to the next iteration- Use
breakfor search/find patterns - Use
continueto skip unwanted values