Patterns as words
Lesson 5 Loops as words
filter, map, find, any, all, count and sum, in loop form and in one-line form
What you'll learn
- Name a loop at a glance: filter, map, find, any, all, count or sum
- Turn the long loop form into its one-word form and back
- Spot the loops an AI got subtly wrong
Most loops in AI-written code are one of seven words. Once you can name the word, you don't read the loop, you recognise it.
The idea
Seven words cover most loops. filter keeps some items. map changes every item. find returns the first match. any asks if at least one matches. all asks if every one matches. count says how many match. sum adds them up. The long form is a for loop with an if or an accumulator; the short form is one call. They mean the same thing.
To name a loop, look at what it builds and what its if asks. A loop that pushes only some items is a filter. One that pushes a changed item for every item is a map.
1const names = [];2for (const user of users) {3 if (user.active) {4 names.push(user.name);5 }6}78// the same thing in two words:9const sameNames = users10 .filter((u) => u.active)11 .map((u) => u.name);
- Line 3 The
ifasks a question and skips some users: that's a filter. - Line 4 It pushes the name, not the user: that's a map.
- Line 10 In the short form each word is on its own line: keep the active users, then take their names.
Take away
- Seven words: filter, map, find, any, all, count, sum.
- Ask what the loop builds and what its
ifasks. - Read the word, then check only what can differ: the condition, and what comes back when nothing matches.
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.