Skip to content
Trace code in your head

Lesson 2.3

Decisions inside loops

7 min · 7 steps

  1. Step 1 of 7 · Explanation

    There are three ways to leave the normal flow of a loop:

    • continue jumps to the next round.
    • break leaves this loop only. Code after the loop still runs.
    • return leaves the whole function, right now.

    Example: a loop adds up [3, -1, 4, 0, 5]. It skips negatives with continue and stops at 0 with break. So -1 is skipped, 5 is never looked at, and the sum is 3 + 4 = 7.

  2. Step 2 of 7 · Predict the result

    Same code. What does it return for [2, 0, -3, 6]?

    function solution(nums) {  let sum = 0  for (let i = 0; i < nums.length; i++) {    if (nums[i] < 0) continue    if (nums[i] === 0) break    sum += nums[i]  }  return sum}
    1. 2
    2. 8
    3. 5
  3. Step 3 of 7 · Predict the result

    break inside nested loops. What does it return for [[1, 0, 1], [1, 1]]?

    function solution(grid) {  let count = 0  for (let r = 0; r < grid.length; r++) {    for (let c = 0; c < grid[r].length; c++) {      if (grid[r][c] === 0) break      count++    }  }  return count}
    1. 3
    2. 1
    3. 4
  4. Step 4 of 7 · Find the bug

    Problem "Return the index of the first even number, or -1." For [3, 4, 6] this code returns 2, but it should be 1. Tap the wrong line.

    function solution(nums) {  let found = -1  for (let i = 0; i < nums.length; i++) {    if (nums[i] % 2 === 0) {      found = i      continue    }  }  return found}
  5. Step 5 of 7 · Predict the result

    Problem "Return true if every number is positive." What does this code return for [-1, 4]?

    function solution(nums) {  let allPositive = true  for (let i = 0; i < nums.length; i++) {    if (nums[i] <= 0) {      allPositive = false    } else {      allPositive = true    }  }  return allPositive}
    1. true
    2. false
  6. Step 6 of 7 · Arrange the code

    Build a function that returns true if any word has more than 5 letters. Use an early return. Two lines don't belong.

    for (let i = 0; i < words.length; i++) {if (words[i].length > 5) return truereturn false}}return trueif (words[i].length > 5) return falsefunction solution(words) {
  7. Step 7 of 7 · Recap

    • continue jumps to the next round. break leaves one loop. return leaves the function.
    • break in nested loops only leaves the inner loop.
    • An "all" or "any" flag only flips one way. An early return is usually clearer than a flag.

    Pattern card

    Early return
    When to use it: When the answer is already certain in the middle of the loop. Return inside the loop, and put the "not found" answer after it.
    for (const x of items) {  if (matches(x)) return true}return false