Easy

FizzBuzz

Prompt

Write a function fizzBuzz(n) that returns:

  • "Fizz" if n is divisible by 3
  • "Buzz" if n is divisible by 5
  • "FizzBuzz" if n is divisible by both 3 and 5
  • The number itself otherwise

Playground

Hint 1

The modulo operator % gives you the remainder of a division. If n % 3 === 0, the number is divisible by 3.

Hint 2

The order of your if statements matters. Think about what happens if you check for divisibility by 3 before checking for divisibility by both 3 and 5.

Solution

Explanation

FizzBuzz is probably the most famous interview question in programming. The solution is just a chain of if statements, but there's one catch that trips people up.

Each check uses the modulo operator %. If you haven't used it much, % gives you the remainder after division. 15 % 3 is 0 because 15 divides evenly by 3 with nothing left over. 7 % 3 is 1 because 7 divided by 3 is 2 with a remainder of 1. So n % 3 === 0 is just asking "does n divide evenly by 3?"

The trap is the order. You must check for "divisible by both 3 and 5" first. Here's why:

// Wrong order:
if (n % 3 === 0) return 'Fizz'; // catches 15!
if (n % 5 === 0) return 'Buzz';
if (n % 3 === 0 && n % 5 === 0) return 'FizzBuzz'; // never reached for 15

If you put n % 3 === 0 first and pass 15, it matches (because 15 is divisible by 3) and returns "Fizz". The function exits early and never gets to the FizzBuzz check. But 15 should return "FizzBuzz" because it's divisible by both.

By putting the combined check first, we catch numbers like 15 and 30 before they get caught by the individual Fizz or Buzz checks:

// Correct order:
if (n % 3 === 0 && n % 5 === 0) return 'FizzBuzz'; // catches 15 first
if (n % 3 === 0) return 'Fizz';
if (n % 5 === 0) return 'Buzz';
return n;

That's the whole question. The logic is simple, but getting the order right is what the interviewer is watching for.