JavaScript Algorithms: FizzBuzz

Michael Jiang
JavaScript in Plain English
3 min readNov 17, 2020

--

Fizz…Buzz…FizzBuzz? This classic and fun little technical interview question will really tackle your understanding of the modulus operator!

Photo by Crissy Jarvis

FizzBuzz is a pretty simple interview question that comes up often. It’s one of those questions that after you see the answer once, you’ll always remember how to solve it from then on out. The only tricky part about this entire problem is the usage of the modulus operator. According to the MDN Web Docs, the modulus/remainder operator (%) returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend. So if I write 12 % 5, it will return 2 because 5 goes into 12 twice with a remainder of 2. With that said, let’s get started:

Write a function that prints out a number from 1 to x. However, you must abide by these rules:

For every multiple of 3, print “fizz” instead of the number.
For every multiple of 5, print “buzz” instead of the number.
For every multiple of both 3 and 5, print “fizzbuzz” instead of the number.

For example, fizzBuzz(5) will return:

1
2
fizz
4
buzz

If we break up the question into smaller parts, the very first part is simply iterating from 1 to x. That can be easily accomplished using a manual for loop:

Within the for loop, we’re going to set a few conditions. Specifically, the conditions where the number being printed out is a multiple of 3, 5, or 3 and 5 (which is basically 15). These conditions will be using the modulo operator because at any point, if the number being printed out is divisible by 3, 5, or 15, then the modulo should return 0. Let’s implement those conditions:

Lastly, we want to make sure that we print out the number if none of the conditions match, which is why we have a console.log(i) at the end.

If we run through with the example of fizzBuzz(5), we start with 1 going through the conditionals. Because it does not satisfy any of the conditions, it will be printed out. The same happens for 2. Once we hit 3, because 3 modulo 3 gives us 0, the condition becomes true and we will print out fizz instead. 4 Also does not satisfy any conditions, so it will be printed out again. When we hit 5, 5 modulo 5 is equal to 0, so that condition also returns true, therefore printing out buzz.

This question is short and sweet, but I think it segues very well into more complicated algorithms that involve checking for specific cases and catching them using conditional statements.

Next week, I’m going to try and explain recursion!

--

--