Lesson 2.2
Loop boundaries
6 min · 7 steps
Step 1 of 7 · Explanation
An array of length
nhas indexes0ton - 1. So the standard loop isi < nums.length, noti <= nums.length.Most boundary bugs come from three places:
<versus<=, readingnums[i + 1]on the last item, and a backward loop that stops too early.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}"abcundefined""abc""ab"
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}[3, 2][3, 2, 1][2, 1]
Step 4 of 7 · Find the bug
Problem "Return the largest product of two neighbors." For
[3, 6, -2]this code returnsNaN. 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}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}012
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) {Step 7 of 7 · Recap
- Array indexes go from
0tolength - 1. The standard loop isi < length. - If you read
nums[i + 1], stop ati < length - 1. - A backward loop needs
i >= 0. A loop whose condition is false at the start never runs.
- Array indexes go from