Home › Learn › JavaScript › Loops

FizzBuzz

Lesson 15 of 40. The classic loop-and-conditions exercise.

FizzBuzz lists the numbers from 1 to n, but multiples of 3 become Fizz, multiples of 5 become Buzz, and multiples of both become FizzBuzz. It uses a loop, a chain of conditions, and an array being built up.

The trap is order: if you test "multiple of 3" first, 15 becomes Fizz and never reaches FizzBuzz. Test the most specific case first, or build the word from two independent checks and fall back to the number when the word is empty.

Your task

Write fizzbuzz(n) returning an array of strings for 1 to n: "Fizz", "Buzz", "FizzBuzz", or the number as a string (String(i)). fizzbuzz(5) is ["1", "2", "Fizz", "4", "Buzz"].

Hint 1

Check i % 15 === 0 first.

Hint 2

String(i) turns a number into text.

Show the 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;
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.