FizzBuzz

“FizzBuzz”, a White belt challenge from the CurlyScript Dojo. It uses what Grade 5: Loops: Doing Things Over and Over teaches, and 4 tests check your answer.

The challenge

Write fizzBuzz(n) that returns an array for the numbers 1 to n: "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for multiples of both, and the number itself (as a string) otherwise.

Example
fizzBuzz(5)  // ["1", "2", "Fizz", "4", "Buzz"]

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • fizzBuzz(5) gives ["1", "2", "Fizz", "4", "Buzz"]
  • The 15th item is FizzBuzz: fizzBuzz(15)[14] gives "FizzBuzz"
  • fizzBuzz(15).length gives 15
  • fizzBuzz(0) gives []

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

Check “both” first: i % 3 === 0 && i % 5 === 0.

Hint 2

String(i) turns the number into a string. Push each answer into result.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function fizzBuzz(n) {
  const result = [];
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) result.push("FizzBuzz");
    else if (i % 3 === 0) result.push("Fizz");
    else if (i % 5 === 0) result.push("Buzz");
    else result.push(String(i));
  }
  return result;
}

Learn what you need

This exercise uses what Grade 5: Loops: Doing Things Over and Over teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning