Fizz Buzz

Updated 03/07/2023

This is a Rosetta Code post.

Story

A popular interview question is the FizzBuzz test, its based on a children’s game where you count from 1 to 100 and for multiples of 3 say ‘Fizz’, multiples of 5 say “Buzz”, if both say ‘FizzBuzz’ else say the number.

For example, a typical round of fizz buzz would start as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1         
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz Buzz
...

Task

Write a program that prints the numbers from 1 to n. But for multiples of three print Fizz instead of the number and for the multiples of five print Buzz. For numbers which are multiples of both three and five print FizzBuzz.

Solutions

Iterative

  • fizzbuzz_iterative.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export const getFizzBuzz = (upperBound) => {
let outPut = "";

for (let i = 1; i <= upperBound; i++) {
outPut = "";

if (i % 3 == 0)
outPut = "Fizz";

if (i % 5 == 0)
outPut += "Buzz";

if (outPut == "")
outPut = i;

console.log(outPut);
}
}
  • index.js
1
2
3
import {getFizzBuzz} from "./fizzbuzz_recursive.js"

getFizzBuzz(15);

Recursive

Recursive solution based on code from Chinmay Deshmukh, his was cooler because it used Typescript.

  • fizzbuzz_recursive.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export const getFizzBuzz = (totalNumber, currentNumber = 1) => {

if (currentNumber > totalNumber) return;

if ((currentNumber % 3 == 0) && (currentNumber % 5 == 0)) {
console.log("Fizz Buzz");
} else if (currentNumber % 3 == 0) {
console.log("Fizz");
} else if (currentNumber % 5 == 0) {
console.log("Buzz");
} else {
console.log(currentNumber);
}

getFizzBuzz(totalNumber, currentNumber + 1);
}
  • index.js
1
2
3
import {getFizzBuzz} from "./fizzbuzz_recursive.js"

getFizzBuzz(15);

References