Skip to content
Trace code in your head

Lesson 2.2

Loop boundaries

6 min · 7 steps

  1. Step 1 of 7 · Explanation

    An array of length n has indexes 0 to n - 1. So the standard loop is i < nums.length, not i <= nums.length.

    Most boundary bugs come from three places: < versus <=, reading nums[i + 1] on the last item, and a backward loop that stops too early.

  2. Step 2 of 7 · Predict the result

    Notice the <=. What does it return for "abc"?

    function solution(s) {  let out = ""  for (let i = 0; i <= s.length; i++) {    out += s[i]  }  return out}
    1. "abcundefined"
    2. "abc"
    3. "ab"
  3. Step 3 of 7 · Predict the result

    A backward loop. What does it return for [1, 2, 3]?

    function solution(nums) {  const out = []  for (let i = nums.length - 1; i > 0; i--) {    out.push(nums[i])  }  return out}
    1. [3, 2]
    2. [3, 2, 1]
    3. [2, 1]
  4. Step 4 of 7 · Find the bug

    Problem "Return the largest product of two neighbors." For [3, 6, -2] this code returns NaN. Tap the wrong line.

    function solution(nums) {  let best = -Infinity  for (let i = 0; i < nums.length; i++) {    best = Math.max(best, nums[i] * nums[i + 1])  }  return best}
  5. Step 5 of 7 · Predict the result

    What does it return for n = 5?

    function solution(n) {  let count = 0  for (let i = n; i < 3; i++) {    count++  }  return count}
    1. 0
    2. 1
    3. 2
  6. Step 6 of 7 · Arrange the code

    Build a function that returns the sum of each pair of neighbors. [1, 2, 3] becomes [3, 5]. Two lines don't belong.

    for (let i = 0; i < nums.length; i++) {const out = []for (let i = 1; i < nums.length - 1; i++) {}return outout.push(nums[i] + nums[i + 1])for (let i = 0; i < nums.length - 1; i++) {}function solution(nums) {
  7. Step 7 of 7 · Recap

    • Array indexes go from 0 to length - 1. The standard loop is i < length.
    • If you read nums[i + 1], stop at i < length - 1.
    • A backward loop needs i >= 0. A loop whose condition is false at the start never runs.

    Pattern card

    Check the loop bounds
    When to use it: Every time you write a loop. Trace just the first and the last round, since boundary bugs always live there.
    for (let i = 0; i < n; i++)          // 0 .. n-1for (let i = 0; i < n - 1; i++)      // pakai / uses nums[i + 1]for (let i = n - 1; i >= 0; i--)     // mundur / backward