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.
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.
It prints
What the tests check
fizzBuzz(5)gives["1", "2", "Fizz", "4", "Buzz"]- The 15th item is FizzBuzz:
fizzBuzz(15)[14]gives"FizzBuzz" fizzBuzz(15).lengthgives15fizzBuzz(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
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.