DEV Community

Zechariah Hounwanou
Zechariah Hounwanou

Posted on • Originally published at codexive.hashnode.dev on

Solving FizzBuzz Problem in JavaScript

We are going to play a game called FizzBuzz, Have you played the game before, if you havent no need to worry I will show you how. I can tell you for free that afterward you would love to play it and write a program code for it in your favorite programming language, its so enticing.

In this game we are going to start by counting from 1 and saying each number out loud but here is where the fun comes in when we get to a number that is a multiple of 3, instead of saying that number itself we say the word Fizz! And when we get to a number that is a multiple of 5 we say the word Buzz! if a number is then a multiple of both 3 and 5 we say the word FizzBuzz! cool right? I know.

My preferred language is Javascript so let's write a program to play the game using my language. Any programming will do the trick but I choose to use JS.

First, we need to tell the computer that we want to start the counting of numbers from 1. We can do that by creating a variable called count and setting it up with the value of 1.

let count = 1

Enter fullscreen mode Exit fullscreen mode

Next, we need to write out the logic that will make our program say the numbers and FizzBuzz when appropriate. We can use a loop to go through all the numbers from 1 which is the count value to 100 (or any other number we wish to play up to). Inside the loop, we want to use an IF statement to check if the current number is a multiple of 3, 5, or both. If it is we can then use the console.log command to make the program say either Fizz, Buzz or FizzBuzz. Now let's write the code down

for(let count = 1; count <= 100; count++){
    if(count % 3 === 0 && count % 5 === 0){
        console.log("FizzBuzz");
    } else if (count % 3 === 0){
        console.log("Fizz");
    } else if (count % 5 === 0){
        console.log("Buzz");
    } else {
        console.log(count);
    }
}

Enter fullscreen mode Exit fullscreen mode

Our code is ready to be shipped by the power in 0s and 1s. Now when we run this program, our computer will play the FizzBuzz game for us! We can change the number we wish to play with by changing the number in the loop. For example, if we want to play up to 50, we can change the loop to:

for(let count = 1; count <= 50; count++){
    //FizzBuzz Logic as above goes here
}

Enter fullscreen mode Exit fullscreen mode

And thats it, my fellow developers, we have just created a FizzBuzz game program that we can play using JavaScript. Have fun coding!

Top comments (0)