मुख्य सामग्री पर जाएं
eLearner.app
मॉड्यूल 5 · पाठ 3 का 4पाठ्यक्रम में 19/32~10 min
मॉड्यूल पाठ (3/4)

तोड़ो और जारी रखो

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

व्यायाम#js.m5.l3.e1
प्रयास: 0लोड हो रहा है...

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

संपादक लोड हो रहा है...
संकेत दिखाएँ

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

3 प्रयासों के बाद समाधान उपलब्ध है

Review exercise

व्यायाम#js.m5.l3.e2
प्रयास: 0लोड हो रहा है...

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

संपादक लोड हो रहा है...
संकेत दिखाएँ

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

3 प्रयासों के बाद समाधान उपलब्ध है