FizzBuzz
Prompt
Write a function named fizzBuzz
in JavaScript that takes a number as an argument and returns "Fizz" if the number is divisible by 3, "Buzz" if it is divisible by 5, and "FizzBuzz" if it is divisible by both 3 and 5. Otherwise, it should return the number itself.
This is perhaps the most common interview question ever.
Requirements
- If
n
is a multiple of 3, it should return "Fizz". - If
n
is a multiple of 5, it should return "Buzz". - If
n
is a multiple of both 3 AND 5, it should return "FizzBuzz". - Otherwise, it should return
n
.
Example
fizzBuzz(3); // "Fizz"
fizzBuzz(5); // "Buzz"
fizzBuzz(15); // "FizzBuzz"
fizzBuzz(7); // 7
Playground
Don't overcomplicate this one. The problem can be solved with a chain of if/else-if statements.
Solution
Explanation
The way I would solve this is by translating the requirements into the code. Like translating from one language to another.
The first requirement is that if n
is a multiple of 3, it should return "Fizz".
if (n % 3 === 0) {
return 'Fizz';
}
The second requirement is that if n
is a multiple of 5, it should return "Buzz".
if (n % 5 === 0) {
return 'Buzz';
}
The third requirement is that if n
is a multiple of both 3 and 5, it should return "FizzBuzz".
if (n % 3 === 0 && n % 5 === 0) {
return 'FizzBuzz';
}
And finally, if n
is not a multiple of 3 or 5, it should return n
.
return n;
However, there is one catch, the order of the if/else-if
statements is important.
Let's assume we pass the number 15 to the fizzBuzz
function and our first condition is if(n % 3 === 0)
.
The first condition will catch it and return "Fizz", because 15 is divisible by 3. This way we returned early and never reached the second and third condition.
What we need to do is to lift the condition for n % 3 === 0 && n % 5 === 0
to the top of the function for the function to work correctly.