Ana içeriğe geç
eLearner.app
Modül 5 · Ders 3 ders 4Kurstaki 19/32~10 min
Modül dersleri (3/4)

ara ver ve devam et

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

Egzersiz#js.m5.l3.e1
Denemeler: 0Yükleniyor…

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

Düzenleyici yükleniyor…
İpucu göster

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

3 denemeden sonra çözüm mevcut

Review exercise

Egzersiz#js.m5.l3.e2
Denemeler: 0Yükleniyor…

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

Düzenleyici yükleniyor…
İpucu göster

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

3 denemeden sonra çözüm mevcut