ILILCode

Loops: repeat without repeating yourself

for, while, for...of and for...in — and how to build up an array one item at a time.

Lesson 5 of 23 in JavaScript10 min1 exercise

A for loop is the classic: start a counter, keep going while a condition holds, step the counter each round.

Counting up
for (let i = 1; i <= 3; i++) {
  console.log(i); // 1, 2, 3
}

When you need to walk the values of an array, for...of says it directly. for...in walks keys and is meant for plain objects, not arrays.

Three ways to repeat
const fruits = ["apple", "pear", "plum"];

for (const fruit of fruits) {
  console.log(fruit); // each value
}

for (const index in fruits) {
  console.log(index); // "0", "1", "2"
}

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

break leaves the loop early; continue skips to the next round. A very common pattern is an empty array you fill inside the loop.

Building a result
const doubled = [];
for (const n of [1, 2, 3]) {
  doubled.push(n * 2);
}
console.log(doubled); // [2, 4, 6]

Try it

FizzBuzz, the classic warm-up

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

FizzBuzz, collected

Write fizzbuzz(n) that returns an array of strings for the numbers 1 to n:

  • multiples of 3 and 5 → "FizzBuzz"
  • multiples of 3 → "Fizz"
  • multiples of 5 → "Buzz"
  • everything else → the number as a string, e.g. "7"

fizzbuzz(5) → ["1", "2", "Fizz", "4", "Buzz"]. fizzbuzz(0) → [].

exercise.js
console · run your code or check the answer