Search⌘ K
AI Features

Break and Continue

Explore how to apply break and continue statements in JavaScript loops to control the flow of iteration. Understand how break exits the loop and continue skips specific iterations, improving your loop efficiency and coding clarity.

We'll cover the following...

Introduction

We can use break or continue inside the loops:

  • break exits the closest loop it is in and continues with the next command,
  • continue skips out from the loop body and jumps back to the condition of the loop.

Example: sum every second element of the numbers array:

Node.js
let numbers = [19, 65, 9, 17, 4, 1, 2, 6, 1, 9, 9, 2, 1];
function sumArray( values ) {
let sum = 0;
for ( let i in values ) {
if ( i % 2 == 0 ) continue;
sum += values[i];
}
return sum;
}
console.log("The sum is", sumArray( numbers ));

Continue

This ...