Skip to main content
eLearner.app
Module 5 · Lesson 3 of 419/32 in the course~10 min
Module lessons (3/4)

break and continue

Two very useful little words inside a loop:

  • break exits the innermost loop immediately.
  • continue jumps to the next iteration, without executing the rest of the body.

break: exit early

Typical for "find the first one that satisfies a condition":

JS
function primoNegativo(nums) {
  for (const n of nums) {
    if (n < 0) return n; // o: result = n; break;
  }
  return undefined;
}

primoNegativo([3, 7, -2, 4, -9]); // -2

Example with explicit break:

JS
let trovato = -1;
const nums = [10, 20, 30, 40, 50];
for (let i = 0; i < nums.length; i++) {
  if (nums[i] === 30) {
    trovato = i;
    break;
  }
}
trovato; // 2

continue: skip to the next

When an element is not interesting but you want to keep looping:

JS
function sommaPari(nums) {
  let totale = 0;
  for (const n of nums) {
    if (n % 2 !== 0) continue; // salta i dispari
    totale += n;
  }
  return totale;
}

sommaPari([1, 2, 3, 4, 5, 6]); // 12

In many cases an if (cond) { ... } would be equivalent; continue helps when the body is long and you want to keep the flow flat (little nesting).

Try it

Exercise#js.m5.l3.e1
Attempts: 0Loading…

Define `firstGreater(nums, threshold)` that returns the first element of nums strictly greater than threshold, or undefined if none is. Use break (or an immediate return).

Loading editor…
Show hint

A return inside the for works as break + return at the same time.

Solution available after 3 attempts

Review exercise

Exercise#js.m5.l3.e2
Attempts: 0Loading…

Define `sumSkippingZeros(nums)` that sums all elements except the exact zeros. Use continue.

Loading editor…
Show hint

If n === 0, continue; otherwise accumulate.

Solution available after 3 attempts