In JavaScript, the “break” and “continue” statements are used to modify the behavior of loops.
The “break” statement is used to immediately terminate the execution of a loop. When the “break” statement is encountered, control is transferred to the statement immediately following the loop. Here’s an example:
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
In this code, the loop will iterate from 1 to 10. However, when “i” equals 5, the “break” statement will be executed, and the loop will immediately terminate. Therefore, the output will be:
1
2
3
4
The “continue” statement is used to skip over a particular iteration of a loop. When the “continue” statement is encountered, control is transferred to the next iteration of the loop. Here’s an example:
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}
In this code, the loop will iterate from 1 to 10. However, when “i” is an even number, the “continue” statement will be executed, and the current iteration of the loop will be skipped. Therefore, the output will be:
1
3
5
7
9
Both “break” and “continue” statements can be used with “for” loops, “while” loops, and “do…while” loops. They can help you to control the flow of your code and create more efficient and effective loops.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.