Loops: for, while and for…of

Add up an array with a counting for loop, count down with while, and stop a for…of loop early with break.

JavaScript · beginner · 7 min · 24 steps · free

What you'll learn

Loops.js

const prices = [4, 10, 7];
let total = 0;
for (let i = 0; i < prices.length; i++) {
  total += prices[i];
}

let countdown = 3;
while (countdown > 0) {
  console.log(countdown);
  countdown--;
}

for (const price of prices) {
  if (price > 8) break;
  console.log('cheap:', price);
}

Step by step

  1. prices is created and points to a new Array: [4, 10, 7].
  2. total is created with the value 0.
  3. The for loop starts with i = 0 and checks i < prices.length (3) before every pass.
  4. total += prices[i] adds the price at index 0: total = 4.
  5. i < prices.length is true, so the loop body runs.
  6. total changes from 4 to 14.
  7. i < prices.length is true, so the loop body runs.
  8. total changes from 14 to 21.
  9. i is 3 now, and 3 < 3 is false: the loop ends.
  10. countdown is created with the value 3. i goes out of scope and disappears.
  11. while keeps running its body as long as the condition is true.
  12. It prints 3.
  13. countdown changes from 3 to 2.
  14. countdown > 0 is true, so the loop body runs.
  15. It prints 2.
  16. countdown changes from 2 to 1.
  17. countdown > 0 is true, so the loop body runs.
  18. It prints 1.
  19. countdown changes from 1 to 0.
  20. countdown > 0 is false, so the loop ends.
  21. for…of gives each value of the array in turn, with no index to manage.
  22. price > 8 is false, so the if-block is skipped.
  23. It prints cheap: 4.
  24. 10 > 8, so break ends the loop at once. 7 is never looked at.

Common mistakes

Best practices

Key takeaways

Check yourself

for (let i = 0; i < 2; i++) runs how many times?

Answer: 2

continue does what?

Answer: Skips to the next pass

·

More in The Basics