Home › Learn › JavaScript › Loops

break and continue

Lesson 13 of 40. Leave a loop early, or skip one round.

break ends the loop at once; continue skips the rest of the current round and moves to the next. Both work in for and while loops. A search loop usually returns from inside the loop when it finds the item and returns the "not found" value after the loop.

Returning null for "nothing found" is the JavaScript convention (undefined also appears, mostly from built-ins like Array.prototype.find).

for (const word of ["hi", "stop", "never"]) {
  if (word === "stop") break;
  console.log(word);      // only "hi"
}
for (let n = 0; n < 5; n++) {
  if (n % 2 === 0) continue;
  console.log(n);         // 1, 3
}

Your task

Write firstNegative(nums) returning the first number below zero or null when there is none, and sumPositive(nums) adding up only the numbers greater than zero, skipping the rest with continue.

Hint 1

for (const n of nums) { if (n < 0) return n; } return null;

Hint 2

if (n <= 0) continue; total += n;

Show the solution
function firstNegative(nums) {
  for (const n of nums) {
    if (n < 0) return n;
  }
  return null;
}

function sumPositive(nums) {
  let total = 0;
  for (const n of nums) {
    if (n <= 0) continue;
    total += n;
  }
  return total;
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.