Direct naar de hoofdinhoud
eLearner.app
Module 5 · Les 3 van 419/32 in de cursus~10 min
Modulelessen (3/4)

breken en doorgaan

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

Oefening#js.m5.l3.e1
Pogingen: 0Laden…

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).

Editor laden…
Toon hint

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

Oplossing beschikbaar na 3 pogingen

Review exercise

Oefening#js.m5.l3.e2
Pogingen: 0Laden…

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

Editor laden…
Toon hint

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

Oplossing beschikbaar na 3 pogingen