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:

  1. The variable tracker
  2. The condition
  3. 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:

const temps = [22, 25, 19, 18, 23];

let index = 0;

while (index < temps.length) {
  console.log(`The temp is: ${temps[index]} degrees`)
  index++;
}

Compare that code to the for loop below. Do you see much difference?

for (let i = temps.length - 1; i >= 0; i--) {
  console.log(`The temp is: ${temps[i]} degrees`)
}

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:

for (const temp of temps) {
  console.log(`The temp is: ${temp} degrees`)
}

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?