AI Hints
Home›JavaScript Tutorial›Practice: Control Flow
JavaScript · Lesson 28 of 138

Practice: FizzBuzz

Loops and ifs.

⏱ 2 min read▶ Video at 33:42🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

FizzBuzz is a famous beginner challenge, and a classic interview warm up. Count from one to fifteen. For multiples of three, print Fizz. For multiples of five, print Buzz. For multiples of both, print FizzBuzz. Otherwise, print the number. Pause and try it.

Practice: FizzBuzz
From the video: Practice: FizzBuzz
  • Count from 1 to 15
  • 3: Fizz, 5: Buzz
  • Both: FizzBuzz

A solution

The key is the order of the checks. We check for multiples of both three and five first, using fifteen. If we checked three first, fifteen would just print Fizz. Then three, then five, and otherwise the number. Run it.

app.jsjavascript
for (let i = 1; i <= 15; i++) {
  if (i % 15 === 0) {
    console.log("FizzBuzz");
  } else if (i % 3 === 0) {
    console.log("Fizz");
  } else if (i % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
}
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

What it tests

FizzBuzz looks simple, but it tests three key skills. Loops, the remainder operator, and putting conditions in the right order. If you could solve it, you've already learned the core of control flow. Well done.

keyvalue
Loop1 to 15
Remainderi % 3 === 0
Ordercheck 15 first
Core skillscovered

A shorter FizzBuzz

Here's another way to write it, which is easy to extend. We build up a word. If the number divides by three, add Fizz. If it divides by five, add Buzz. If the word is still empty, use the number instead. Adding a new rule, like Bazz for seven, would just be one more line. Run it.

app.jsjavascript
for (let i = 1; i <= 15; i++) {
  let word = "";
  if (i % 3 === 0) word += "Fizz";
  if (i % 5 === 0) word += "Buzz";
  console.log(word || i);
}
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Summary

FizzBuzz combines a loop, the remainder operator, and ordered conditions. Next, loops inside loops.

Key takeaways
  • % for multiples
  • Most specific first
  • else for the rest
Next up: Practice: Times Tables — nested loops