Lesson 2.3
Decisions inside loops
7 min · 7 steps
Step 1 of 7 · Explanation
There are three ways to leave the normal flow of a loop:
continuejumps to the next round.breakleaves this loop only. Code after the loop still runs.returnleaves the whole function, right now.
Example: a loop adds up
[3, -1, 4, 0, 5]. It skips negatives withcontinueand stops at 0 withbreak. So -1 is skipped, 5 is never looked at, and the sum is 3 + 4 = 7.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}285
Step 3 of 7 · Predict the result
breakinside 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}314
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}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}truefalse
Step 6 of 7 · Arrange the code
Build a function that returns
trueif 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) {Step 7 of 7 · Recap
continuejumps to the next round.breakleaves one loop.returnleaves the function.breakin 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.