Ah, the good ol' FizzBuzz challenge. It's a classic test across all programming languages. It exists only to verify that you can actually write code in your chosen language. In case you haven't seen it before, here's the most popular version:

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Matt Mullenweg—CEO of Automattic—said in an episode of The Tim Ferriss Show that a surprising number of people fail this challenge:

You move some variables around that are fizz and buzz and you arrange them in different ways, or you repeat them, or you sort an array or something like that. But a basic thing that anyone can figure out. And that filters out a surprising number of people even who make it through these first few screens. Simple coding test.

There are hundreds of articles about this already, but I thought I might as well weigh in with my two cents. I'll show you my approach, then I'll point out a few things. It's not especially clever, but that's the idea. Don't try to be clever. If there's more than one way to accomplish a task, always go with the simplest version.

Here's my approach:

for (let number = 1; number <= 100; number++) {
let message;

if (number % 15 === 0) {
message = "FizzBuzz";
} else if (number % 3 === 0) {
message = "Fizz";
} else if (number % 5 === 0) {
message = "Buzz";
} else {
message = number;
}

console.log(message);
}

You can view a demo on CodePen.

A few things to note:

  • The let statements ensure that the number and message variables are block-scoped to the loop.
  • Although the variable name i is common within a for loop, I opted for number because it's more explicit in this case.
  • The message variable ensures that I only need to write one call to console.log() at the end, rather than four times in total (once for each conditional block).