09 Loop Break and Continue

Here are five examples demonstrating the use of `break` and `continue` in JavaScript loops, ranging from easy to hard. Each example outputs directly to the browser using `document.write`.


 

---


 

### 1. **Break in a For Loop** - Easy
```javascript
document.write("<h3>Break in a For Loop</h3>");
for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        document.write("Loop stopped at: " + i);
        break;
    }
    document.write(i + "<br>");
}
```


 

---


 

### 2. **Continue in a For Loop** - Easy
```javascript
document.write("<h3>Continue in a For Loop</h3>");
document.write("Numbers except 5:<br>");
for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        continue;
    }
    document.write(i + "<br>");
}
```


 

---


 

### 3. **Break in a While Loop** - Medium
```javascript
document.write("<h3>Break in a While Loop</h3>");
let num = 1;
while (num <= 10) {
    if (num === 7) {
        document.write("Stopped at number: " + num);
        break;
    }
    document.write(num + "<br>");
    num++;
}
```


 

---


 

### 4. **Continue in a While Loop** - Medium
```javascript
document.write("<h3>Continue in a While Loop</h3>");
let count = 0;
document.write("Skipping multiples of 3:<br>");
while (count < 10) {
    count++;
    if (count % 3 === 0) {
        continue;
    }
    document.write(count + "<br>");
}
```


 

---


 

### 5. **Nested Loops with Break and Continue** - Hard
```javascript
document.write("<h3>Nested Loops with Break and Continue</h3>");
outer: for (let i = 1; i <= 3; i++) {
    for (let j = 1; j <= 3; j++) {
        if (i === 2 && j === 2) {
            document.write("Breaking outer loop at i=" + i + ", j=" + j + "<br>");
            break outer;
        }
        if (j === 2) {
            continue;
        }
        document.write("i=" + i + ", j=" + j + "<br>");
    }
}
```


 

---


 

Copy and paste these examples into an HTML file to see them displayed in your browser! 😊
2 min read
Nov 19, 2024
By Md Real
Share

Leave a comment

Your email address will not be published. Required fields are marked *