DevNotes
@devnotes ·
JavaScript Part 4: Repeat things with loops
Print a times table, add up a bill, check every item in a list: loops run the same code many times without you writing it many times.
The for loop
The brackets hold three parts, separated by semicolons:
let i = 1runs once, before the loop starts.i <= 5is checked before every round. As soon as it's false, the loop stops.i++runs after every round. It's short fori = i + 1.
So this prints the 7 times table, from 1 to 5. Loop counters are traditionally called i, and that's one of the few places where a one-letter name is fine.
Looping over a list: for...of
Most of the time you're looping over items, not counting:
for...of hands you each item in turn, so there's no counter to get wrong. total += price is short for total = total + price. Arrays get their own part soon; for now, read [120, 80, 250] as a list of three prices.
The while loop
while keeps going as long as its condition is true. Reach for it when you can't know in advance how many rounds you'll need:
At 10% interest a year, this counts how many years it takes for 1000 rupees to double. You couldn't know that number before running the code, and that's exactly when while fits.
break and continue
break ends the loop right away. continue skips the rest of the current round and moves on to the next one.
The infinite loop
If the condition never becomes false, the loop never ends, and the page freezes:
Everyone writes one of these sooner or later. If a tab freezes, close it, find the loop, and check that something inside it moves the condition towards false.
Try it
Write a loop that adds up every number from 1 to 100 and prints the total. You should get 5050. Then change it to add only the even numbers.
Next: JavaScript Part 5: Functions
Join WIK to like and reply to DevNotes and see more like this.