Buzzing Over FizzBuzz? Start Here.

Niani Byrd
3 min readSep 24, 2021

FizzBuzz might be the most commonly known interview question for developers and engineers. I recently interviewed for a position and a variation of this question was the first coding question that they asked me. You might be wondering….how in the world do I solve it? Odds are, you might be overcomplicating it (because I definitely did the same thing). Read this post to see how I solve this popular question in JavaScript!

Lets take a look at the question down below.

Write a program that console logs the numbers from 1 to n. 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”.

The first and most paramount task is to understand the mathematics behind the question. We need to figure out all the multiples of 3, 5, and both 3 AND 5. In order to do this, we have a superstar operator that will make solving this problem 1000x easier.

Enter……MODULO.

It looks like the percentage sign: %. The key to solving this problem is knowing exactly how to use the modulo operator. In order to figure out if a number is a multiple of 3, 5, or both. The modulo operator will return the remainder left over when one operand is divided by a second operand. So lets say for example you have 9 % 3. The answer would be 0 because 3 goes into 9 exactly 3 times, with nothing left over. Now what if we had 10 % 3? The answer is now 1 because 3 goes into 10 3 times, with 1 leftover. We will use this exact operation when coding the answer to FizzBuzz.

First, we begin with a for loop to iterate over an array that start at 1, ends at n, and increments by 1.

function fizzBuzz(n) {for (let i =1; i <= n; i++) {
}
}

Within the for loop, write an if/else statement for each condition (multiples of 3, 5 and 15).

function fizzBuzz(n) {  for (let i =1; i <= n; i++) {    if (i % 3 === 0 && i % 5 === 0) {
//Is this number a multiple of 3 AND 5?
console.log('fizzbuzz') } else if ( i % 3 === 0 ) {
//Is this number a multiple of 3?
console.log('fizz') } else if (i % 5 === 0 ) {
//Is this number a multiple of 5?
console.log('buzz') } else { console.log(i) }
}
}

So, let’s break down the code. We use i as our variable. If there is no remainder of i % 3 AND i % 5, we can print FizzBuzz. The same process will happen three times for when we account for each condition that the problem requires. Lastly, the final else statement simply returns i because the problem requires that if the number is neither a multiple of 3, 5 or both, simply return the number.

See? FizzBuzz seems complicated at first, but once you understand the beauty of modulo, the problem becomes simple. Attack each condition one by one, and there you have it! All test cases should be passing. Happy Coding!

--

--