Solving The "FizzBuzz Challenge" Using Javascript

The FizzBuzz Challenge is about a game called the FizzBuzz Game. The game has its origin in England (at least, that’s what I’m told). Now, this is how the game works:

Kids come together and stand in a circle, they call out the numbers 1 – 100 sequentially, each taking turns calling the next number I turn. Now, where the FizzBuzz comes in is that for each number that is fully divisible by 3, the kid whose turn it is to call would call out the word “Fizz” instead of the number; for each number that is fully divisible by 5, the kid whose turn it is to call would call out the word “Buzz” instead of the number; and finally, for each number that is fully divisible by both 3 and 5, the kid whose turn it is to call would call out the word “FizzBuzz” instead of the number. Considering javascript, the FizzBuzz Challenge would state something like this:

Write a program that prints the numbers 1 – 100 sequentially. However, for numbers that are multiples of 3, print “Fizz” instead; for multiples of 5, print “Buzz” instead; and then, for multiples of both 3 and 5 (for example, 15, 30, etc), print “FizzBuzz” instead.

This is a nice challenge because it could help you better understand the concept of arrays and functions. This explanation may seem confusing to some initially but just be a bit patient here with me and follow it to the end, OK?  If you do not get it at the first reading, everything will get clearer upon the second reading.

For starters, what we have to ask ourselves is “How can we write a code that prints out a sequence of numbers starting from 1 and every single time we run the code, the next number gets called out?”

To achieve this, let’s create a new array, call it output, and then set it to an empty array.

var output = [ ]; // creates an empty array

Now, we could manually use the array push() function to start adding the numbers and the relevant words where necessary till we get to a hundred but what the hell is that? It’s to repetitive and tedious! For crying out loud, we are programmers! At times like these, it is quite helpful to remember the concept of functions in javascript. So, let’s create a function. However, before we do that, we have to find a way to count the number. So, lets create a variable to hold the numbers as they are printed out.

var count = 1; // creates a variable to store and determine the count. The count right now is the number being called.

Now, lets create the function that would do the counting for us.  

function fizzBuzz () {

                // our goal here is to write a code so that, every single time this function is run, it will add the next number in the sequence to the array called output.

                // We need to add a number that increases by 1 every single time we run the function and we need a variable to keep track of that number. For this, let’s create a global variable called count and let’s assign the value of 1 to it. This would be outside the function (which is that var count = 1 above).

                // Now, we can use the push() function to push (or add) the value of count into our array called output. So, at this point, if we run our code, the output array gets created as an empty array and, when we run the function fizzBuzz(), then 1 will get added to the output array.

output.push(count);

// At this point, no matter how many times we call the function, the value of count would always remain 1 but that is not what we want. We want to increase the sequence of numbers. So, in order to do that, we have to increment count (which could be done using this syntax: count++;).

// Now, whenever we run our code, it will add the next number in the sequence to our array, giving us an output of, say, 1, 2, 3 . . . and so on.

// The next step to consider is how we could get our code to put in the words “Fizz”, “Buzz”, and “FizzBuzz” in the right places.

This is where evaluation comes into place. Now, we have to condition the code. Lets talk briefly about the modulo ( % ) operator. This operator works with divisibility. The modulo is the remainder value after a division has been carried out. So, for example, 5 % 2 = 1 because when 5 divides 2, you have a reminder of 1; 10 % 2 = 0 because when 10 divides 2, you have no remainder. A common way that programmers use the modulo operator is to check whether a number is fully divisible by another number. Get the concept here? So, we can use the same concept in our code in order to check if the current value of count at each stage is fully divisible by 3 individually, 5 individually, and then by both 3 and 5 (or 15); and then, when it is, it will push “Fizz”, “Buzz” and “FizzBuzz” respectively into our output array. That may be your first thought but there’s something you have to ynderstad first about usin the if and if else conditionals. When using the if and if else conditionals, you have to bear in mind that when the program runs the code, the moment that the program gets to a condition that evaluates to true (because all conditionals are booleans), it works in accordance with the specifications of that condition and skips the rest of the code in that code block. Going by this, we have to first set a condition for a scenario where count is fully divisible by both 3 and 5 first before any other condition. This is because, if we set a condition for a scenario whereby count is divisible by 3 (without providing, at the same time, that count is also divisible by 5 at that point), the moment count is fully divisible by 3, the program would skip every other condition (because the condition evaluates to true) and then move on to the next block of code. Following his now, imagine where count is 30. This is a number that is fully divisible by both 3 and 5 individually but, because 30 is fully divisible by 3, the program would simply output “Fizz” and then ignore every other conditional and move on to the next block of code. That’s not what we want here. For this reason, we have to first create a conditional for a scenario whereby the value of count is fully divisible by both 3 and 5 at the same time. However, these evaluations have to be carried out within the fizzBuzz() function before the value of count can be determined and then incremented. So, our next line of code will read:  

                if ( count % 3 === 0 && count % 5 === 0) { // checking for a scenario whereby count is both divisible by both 3 and 5 individually

                output.push(“FizzBuzz”);

}

else if ( count % 3 === 0 ) { // if count is fully divisible by 3

                output.push(“Fizz”); // instead of pushing count, push “Fizz”

}              // Check if the value of count is fully divisible by 5

                else if ( count % 5 === 0 ) {

                output.push(“Buzz”);

}              // At this point, if count is fully divisible by both 3 and 5, the code would only push “Fizz” into the output because computer programs read codes in a descending order. Meaning, following the flow of our conditional statements so far, when count gets to 15, and the program sees that 15 is fully divisible by both 3 and 5, it would follow the instruction and output “FizzBuzz”, and then jump the other conditional statements attached to the first condition that evaluates to true.

                else { 

                output.push(count); // push the actual number, and not "Fizz"

}

count++; // increase the value of count by one after that output

                console.log(output); // prints out the value of output every single time the function is called

}

You have to understand that the order of your if statements matter a huge deal, it is almost like a water flow. The water, or the code, will flow into the conditions and, once it has found a condition that is true, it will skip every other avenue. So, it is important to consider how you order your if statements.

 

At this stage, this is what the final code simply looks like:

var output = [ ];

var count = 1;

 

function fizzBuzz ( ) {

    if (count % 3 === 0 && count % 5 === 0) {

        output.push("FiazzBuzz");

    } else if (count % 3 === 0) {

        output.push("Fizz");

    } else if (count % 5 === 0) {

        output.push("Buzz");

    }

 

    else {

        output.push(count)

    }

 

    count++;

    console.log(output);

}

fizzBuzz();

 

So, that is one way to solve the FizzBuzz Challenge using javascript!


Comments