Target
Write a program that prints the numbers from 1 to 100. 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”.
- Print out numbers 1 to 100
- Replace all numbers divisible by 3 with “Fizz”
- Replace all numbers divisible by 5 with “Buzz”
- replace all numbers divisible by both 3 and 5 with “FizzBuzz”
Solution 1 — Intuitive Approach
Using for loop & if … else … statement
for (var i = 1; i <= 100; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i % 3 === 0) console.log("Fizz");
else if (i % 5 === 0) console.log("Buzz");
else console.log(i);
}
Solution 2 — String Concatenation
Instead of hardcoding the multiple of 15, we used variable here to concatenate the corresponding string.
for (var i = 1; i <= 100; i++) {
let answer = '';
if (i % 3 === 0) answer += "Fizz";
if (i % 5 === 0) answer += "Buzz";
if (!answer) answer = i;
console.log(answer);
}
Solution 3 — Hash all the conditions (Best)
First of all, we store all the conditions in Object.
Then, iterating all of them (both key and value) through Object.entries.
So that we can easily separate our conditions and codes.
map & join
const condition = { 3: "Fizz", 5: "Buzz" };for (var i = 1; i <= 100; i++) {
let answer = Object.entries(condition)
.map(([key, value]) => i % key === 0 ? value : "")
.join("");
if (!answer) answer = i;
console.log(answer);
}
reduce
const condition = { 3: "Fizz", 5: "Buzz" };for (var i = 1; i <= 100; i++) {
let answer = Object.entries(condition)
.reduce((acc, [key, value]) => acc += i % key === 0 ? value : "", "");
if (!answer) answer = i;
console.log(answer);
}
filter & forEach
Changing map & join to filter & forEach plays the same role here.
const condition = { 3: "Fizz", 5: "Buzz" };for (var i = 1; i <= 100; i++) {
let answer = "";
Object.entries(condition)
.filter(([key]) => i % key === 0)
.forEach(([key, value]) => answer += value);
if (!answer) answer = i;
console.log(answer);
}
Performance Test

