JavaScript has break & continue statements to control flow of loops.
The break statement is used to stop execution of loop.
The continue statement is used to move to next iteration in a loop.
We have already seen usage of break statement in switch() statement to stop further execution of switch cases.
It is also used to stop execution of a loop iterations
Whenever a break statement is encounter within loop statements, the execution of loop iteration stops and the code after the loop starts executing
<!DOCTYPE html>
<html>
<body>
Student grads
<p id="text"></p>
<script>
var Student = [95,50,64,85,90];
var studentGrads = [];
for(var i=0; i<Student.length; i++) {
studentGrads[i] = getGrade(Student[i]);
if(Student[i] < 60) {
break;
}
}
document.getElementById('text').innerHTML = studentGrads.toString();
function getGrade(marks) {
if(marks > 90) {
return 'Grade A';
} else if(marks > 80) {
return 'Grade B';
} else if(marks > 70) {
return 'Grade C';
} else if(marks > 60) {
return 'Grade D';
} else {
return 'Fail';
}
}
</script>
</body>
</html>
In above for loop, if the student marks is less than 60, the loop will stop
Continue statement is used to skip iteration based on the condition. Whenever a continue statement is encountered, the loop iteration is moved to next iteration and current iteration stops from that point.
<!DOCTYPE html>
<html>
<body>
Student grads
<p id="text"></p>
<script>
var Student = [95,50,64,85,90];
var studentGrads = [];
for(var i=0; i<Student.length; i++) {
if(Student[i] < 60) {
continue;
}
studentGrads[i] = getGrade(Student[i]);
}
console.log(studentGrads);
document.getElementById('text').innerHTML = studentGrads.toString();
function getGrade(marks) {
if(marks > 90) {
return 'Grade A';
} else if(marks > 80) {
return 'Grade B';
} else if(marks > 70) {
return 'Grade C';
} else if(marks > 60) {
return 'Grade D';
} else {
return 'Fail';
}
}
</script>
</body>
</html>
In above example, if the student marks are less than 60, the loop skip that student.
In JavaScript, statements are labeled with label name and colon(:)
labelname: JavaScript Statements;
The continue statement is used to skip one iteration only whether its used with or without label name.
The break statement is used to skip break loop or switch block.