JavaScript Continue
Continue statement is used to skip the execution of further statements inside the immediate loop and continue with the next iterations.
The syntax of continue statement is
continue;
JavaScript continue statement can be used inside the following statements.
- for
- for in
- for of
- while
- do while
Usually, continue statement is used conditionally inside a loop statement.
We will go through examples with break statement for each of these statements.
Continue For Loop
In the following example, we use continue statement to continue with next iterations of For loop, when i == 4
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
for (let i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
document.getElementById('output').innerHTML += i + ' - hello world\n';
}
</script>
</body>
</html>
Continue For-in Loop
In the following example, we use continue statement to continue with next properties of the object in For-in loop when value == 22
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var obj = {name: 'Apple', age: '22', location: 'California'};
for (key in obj) {
let value = obj[key];
if (value == 22) {
continue;
}
document.getElementById('output').innerHTML += value + '\n';
}
</script>
</body>
</html>
Continue For-of Loop
In the following example, we use continue statement to continue with next items of the iterable object in For-of loop when the value of item is banana
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var obj = ['apple', 'banana', 'orange'];
for (item of obj) {
if (item == 'banana') {
continue;
}
document.getElementById('output').innerHTML += item + '\n';
}
</script>
</body>
</html>
Continue While Loop
In the following example, we use continue statement to continue with next iterations of While loop when i == 5
.
index.html
0
1
2
3
4
6
7
8
9
Continue Do-While Loop
In the following example, we use continue statement to continue with next iterations of Do-While loop when i == 5
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var i = 0;
do {
if (i == 5) {
i++;
continue;
}
document.getElementById('output').innerHTML += i + '\n';
i++;
} while (i < 10);
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned what continue statement is in JavaScript, its syntax, and usage with examples.