DEV Community

Alexandra Fren
Alexandra Fren

Posted on • Originally published at alexandrafren.com

Mastering FizzBuzz

I had heard about "FizzBuzz", of course, but never encountered it in the wild. Recently in a technical interview, I was asked to complete this ubiquitous challenge. I did so in JavaScript, and followed the Red, Green, Refactor pattern to get to my final answer.

The basics of "FizzBuzz" are as follows:

-For a provided input, if divisible by 3, output "Fizz"
-For a provided input, if divisible by 5, output "Buzz"
-For a provided input, if divisible by 3 & 5, output "FizzBuzz"
-All else, output the provided input

The function provided to me in my technical challenge was:

let FizzBuzz = (n) => { return n }

This allowed for the final of the four tests to be passing from the beginning.

I started by writing psuedo-code to gather my thoughts about the best way to solve this. I wrote a conditional statement that evaluated the input based on "divisibility". It's important to note that the conditional for "FizzBuzz" must go first, otherwise the return will end the execution of the function whenever a number is divisible by either 3 or 5 before being able to reach the conditional for both numbers.

let FizzBuzz = (n) => {
 if (n%3 === 0 && n%5 === 0) {
    return "FizzBuzz"
 }
 else if (n%3) {
    return "Fizz"
 }
 else if (n%5) {
     return "Buzz"
 }
 else {
    return n
 } 
}

This alone is sufficient enough to pass the requirements of FizzBuzz, but the number of lines of code can be reduced. Because a return ends the execution of a function, we can remove the else if statements and have 3 if statements. Additionally, because of the simplicity of these conditional statements, we can place all of our code on one line and remove the brackets. This reduces our FizzBuzz function down to four lines of code!

let FizzBuzz = (n) => {
 if (n%3 === 0 && n%5 === 0) return "FizzBuzz"
 if (n%3) return "Fizz"
 if (n%5) return "Buzz"
 else return n
}

While it might seem tempting to just print out the final answer in an interview, going through these steps shows your ability to think logically and how well you can communicate, by talking through the steps you are taking with your interviewer.

Discussion (2)

Collapse
madza profile image
Madza • Edited on

You could also do this:
FizzBuzz=(n)=>[['Fizz'][n%3],['Buzz'][n%5]].join('')||n;

Collapse
notngan profile image
Ngan B. Nguyen

or n%15 === 0