Lesson 1.4
Plan first, then code
6 min · 7 steps
Step 1 of 7 · Explanation
Write a plan in 3 to 5 plain lines before coding. Each plan line later becomes one or two lines of code.
Problem: "Return the longest word. On a tie, return the one that comes first."
- Keep the first word as
best. - Check each word after it.
- If it's longer than
best, replacebest. - Return
best.
Line 3 says "longer", not "as long or longer". That's what keeps the tie rule.
- Keep the first word as
Step 2 of 7 · Arrange the code
Problem: "Return the longest word. On a tie, return the one that comes first."
Plan: keep the first word asbest, check each word after it, replacebestif that word is longer, then returnbest.Build the code. Two lines don't belong.
return bestif (words[i].length >= best.length) {}for (let i = 1; i < words.length; i++) {best = words[i]let best = words[0]}if (words[i].length > best.length) {}for (let i = 1; i <= words.length; i++) {function solution(words) {Step 3 of 7 · Predict the result
What does it return for
["cat", "dog", "ox"]?function solution(words) { let best = words[0] for (let i = 1; i < words.length; i++) { if (words[i].length > best.length) { best = words[i] } } return best}"cat""dog""ox"
Step 4 of 7 · Pick the approach
Problem: "Return the index of the first negative number, or -1 if there isn't one."
Which plan is right?- Check each number. If it's negative, return its index. After the loop ends, return -1.
- Check each number. If it's negative, return its index. If not, return -1.
- Find the smallest number, then return its index.
- Check each number. If
nums[i] <= 0, return its index. After the loop, return -1.
Step 5 of 7 · Predict the result
Problem: "Return the index of the first negative number, or -1 if there isn't one." What does this code return for
[4, -2]?function solution(nums) { for (let i = 0; i < nums.length; i++) { if (nums[i] < 0) { return i } else { return -1 } } return -1}-110
Step 6 of 7 · Write the code
solution(words)Turn this plan into code. Problem: "Return how many words in
wordsstart with the lettera."countstarts at 0.- Check each word.
- If its first letter is
"a", add 1. - Return
count.
function solution(words) { // ["apel", "jeruk", "anggur"] -> 2 }Step 7 of 7 · Recap
- Write a 3 to 5 line plan before the code. One plan line, one or two lines of code.
- Words like "longer" or "first" in the plan decide between
>and>=. - The "not found" return goes after the loop, not in an
elseinside it.