In this post, I will outline one way to write a FizzBuzz algorithm in JavaScript. There are multiple ways to solve this problem, and this is just the most basic solution and does not emphasize succinctness. Feel free to comment with your favorite solution to this challenge!
Here goes...
The function should print all numbers from 1 - 100, except:
- For every number divisible only by 3, it will return "Fizz"
- For every number divisible only by 5, it will return "Buzz"
- For every number that is divisible by both 3 AND 5, it will return "FizzBuzz"
Step 1. Create a for-loop.
In this example, the loop will count from 1-100.
for (let i = 1; i <= 100; i++) {
}
Step 2. Create if..else statements inside the loop.
The first will check if the number is divisible by both 3 and 5. We do this first because if we checked for either 3 or 5 first, either Fizz or Buzz would get returned as soon as the condition is satisfied and the function would not continue to check the other conditions.
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
}
The following two will check if the number is divisible by 3, and 5.
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
}
else if (i % 5 === 0) {
console.log("Fizz");
}
Lastly, if the number isn't divisible by 3 and/or 5, the function will print the number.
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
}
else if (i % 5 === 0) {
console.log("Fizz");
} else {
console.log(i);
}
The full code should look like this:
function fizzbuzz(){
for (let i = 1; i <= 100; i++){
if (i % 3 === 0 && i % 5 === 0){
console.log("FizzBuzz");
} else if (i % 3 === 0){
console.log("Fizz");
} else if (i % 5 === 0){
console.log("Buzz");
} else {
console.log(i);
}
}
}
Top comments (2)
hmmm:
ohh thatโs nice!