DEV Community

stuxnat
stuxnat

Posted on

Solving FizzBuzz

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:

  1. For every number divisible only by 3, it will return "Fizz"
  2. For every number divisible only by 5, it will return "Buzz"
  3. 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++) {
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

hmmm:

[...Array(100)].map((_,i=i+1)=>(console.log(
    i++ &&
    !(i%15)?'FizzBuzz':
    !(i%5)?'Buzz':
    !(i%3)?'Fizz':
    i)))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stuxnat profile image
stuxnat

ohh that’s nice!