DevNotes

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

JavaScript
for (let i = 1; i <= 5; i++) {  console.log(`7 x ${i} = ${7 * i}`);}

The brackets hold three parts, separated by semicolons:

  1. let i = 1 runs once, before the loop starts.
  2. i <= 5 is checked before every round. As soon as it's false, the loop stops.
  3. i++ runs after every round. It's short for i = 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:

JavaScript
const prices = [120, 80, 250];let total = 0;
for (const price of prices) {  total += price;}
console.log(total); // 450

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:

JavaScript
let savings = 1000;let years = 0;
while (savings < 2000) {  savings = savings * 1.1;  years++;}
console.log(years); // 8

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

JavaScript
for (const n of [3, 8, -1, 5]) {  if (n < 0) break;  // stop the whole loop  console.log(n);}// prints 3, then 8
for (let i = 1; i <= 10; i++) {  if (i % 2 === 0) continue;  // skip to the next round  console.log(i);}// prints 1, 3, 5, 7, 9

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:

JavaScript
let i = 0;while (i < 5) {  console.log(i);  // forgot i++, so i stays 0 forever}

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

javascriptwebdevbeginners

Join WIK to like and reply to DevNotes and see more like this.