A visual pattern for loops
Once you understand one loop, you understand them all. Yes, they may have some differences in structure and syntax. But if you understand these 3 elements, you can work with any loop:
- The variable tracker
- The condition
- The block
The condition, our surgeon operator, checks a variable or expression inside the wormhole ( ). If we don’t want the code to keep looping, we need to change that variable on each iteration. We saw how we did that in the previous example’s while loop:
Compare that code to the for loop below. Do you see much difference?
They both rely on exactly the same mechanics. A for loop just puts all three elements inside its parentheses:
- the tracker:
let i = temps.length - 1(the last index, because we count from 0) - the condition:
i >= 0 - the change on each iteration:
i--
Leave out the change, and the condition is met forever: an infinite loop 😲. That’s why for loops are so handy for going forwards or backwards through an array - they make you write all three.
The loop you’ll see most: for...of
When you just want each item of an array, for...of handles the tracker, the condition and the change for you:
It still works exactly like our imagimodel - the engine is doing the counting behind the scenes. Can you picture what a loop inside another loop looks like?
