Module lessons (3/4)
break and continue
Two very useful little words inside a loop:
breakexits the innermost loop immediately.continuejumps to the next iteration, without executing the rest of the body.
break: exit early
Typical for "find the first one that satisfies a condition":
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]); // -2Example with explicit break:
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; // 2continue: skip to the next
When an element is not interesting but you want to keep looping:
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]); // 12In 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
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).
Show hint
A return inside the for works as break + return at the same time.
Solution available after 3 attempts
Review exercise
Define `sumSkippingZeros(nums)` that sums all elements except the exact zeros. Use continue.
Show hint
If n === 0, continue; otherwise accumulate.
Solution available after 3 attempts