Learn JavaScript · lesson 24 of 60 · about 9 minutes
Project: FizzBuzz
Put a FizzBuzz game on Sam's page: check how far the visitor wants to count, then build one line with Fizz for 3s and Buzz for 5s.
What you'll learn
- Combine loops and conditions
- Order checks correctly
- Test the edge cases
A game for visitors
Sam's page gets a small game: the visitor types how far to count, from 1 to 30, and the page shows every number on one line, with Fizz for a multiple of 3, Buzz for a multiple of 5 and FizzBuzz for both. It's the classic interview puzzle, FizzBuzz, and it uses everything from this chapter: a loop, decisions in the right order, and a string built up lap by lap.
The rules
Count from 1 to 15. For each number:
- divisible by 3 and 5: print FizzBuzz
- divisible by 3: print Fizz
- divisible by 5: print Buzz
- otherwise: print the number
Check the both-case first, or 15 would just say Fizz.
FizzBuzz
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
FizzBuzzThe game on Sam's page
const countText = "10";
const count = Number(countText);
const fizz = document.querySelector("#fizzbuzz");
if (!Number.isInteger(count) || count < 1 || count > 30) {
fizz.textContent = "Pick a number from 1 to 30";
} else {
let line = "";
for (let n = 1; n <= count; n++) {
if (n % 15 === 0) {
line += " FizzBuzz";
} else if (n % 3 === 0) {
line += " Fizz";
} else if (n % 5 === 0) {
line += " Buzz";
} else {
line += ` ${n}`;
}
}
fizz.textContent = line.trim();
}
Tip
A number divisible by both 3 and 5 is divisible by 15, so i % 15 === 0 is a neat shortcut.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.