FizzBuzz

FizzBuzz

An in depth look of a simple programming exercise.

ยท

11 min read

FizzBuzz. What a buzzword. Perhaps you've heard of it perhaps not. Either way, knowing how to solve this challenge is important: understanding it is paramount.

What is FizzBuzz anyway? FizzBuzz is a programming exercise designed to test the developer's knowledge and understanding of the language they are coding in. What is great about this challenge is that it can be tested across various coding languages (e.g. C++, PHP, and Javascript to name a few) to achieve the same result.

In this walkthrough, we will solve this challenge together and hopefully, you can learn some things along the way. As programmers, we want to be thorough, so together we will go through each step of the solution and explain its purpose to understand WHY we are using our coding logic. I've also added some gotchas along the way! Let's get to it! ๐Ÿ”ฅ

The Challenge ๐Ÿงฉ

FizzBuzz: Print the numbers 1 to 100 in the console. For every number divisible by 3 print Fizz and for every number divisible by 5 print Buzz. If a number is not divisible by either, print the number as it stands.
โœจ Bonus โœจ: For numbers that are both divisible by 3 and 5 print FizzBuzz.

Setup ๐Ÿ› 

We will be solving this challenge with Javascript. My favorite programming language. If you need an environment to quickly run tests I highly suggest Codepen. It allows you to write code in the browser while quickly updating and displaying your results in real-time. Neat!

Let's begin.

Getting Loopy ๐Ÿคช

As mentioned before we want to be able to count from 1 to 100 and print all the numbers within that range. How can we do that? We can reach out and grab the handy "for" loop.

We are using the "for" loop because it provides us with 3 essential features/arguments: a starting point, a condition, and a step.

for (start; condition; step;) {
    // ... loop body ...
}

Start executes once you enter the loop.
Condition is checked upon every iteration/repetition. If the condition is false it stops.
Body contains the logic that runs every time the condition that is met is 'truthy'.
Step Executes after the body on every iteration.

Using the structure of the "for" loop above we will be able to specify our starting point, the condition required to determine the range of 1 to 100, and the step which allows us to build on each iteration. What might that look like?

for (let n = 1; n < 100; n++) {
    console.log(n);
}

Now if this is your first time using a "for" loop it might seem like a lot so let's break it down.

let n = 1; Here we declare that the variable n, our starting point, is equal to one. Therefore our loop begins at 1.
n < 100; Our condition is that as long as a number is less than 100 the loop will continue to run. If it does not it stops.
n++; Our step is key because it contains a very important operator, ++. The ++ operator in Javascript allows us to increase the value of an integer by 1. In this case or variable n is equal to 1 so in every instance of the loop being true the value will be increased by 1.

Check out your console! ๐Ÿ‘€ It should look a little something like this.

1
2
3
... more numbers
98
99

Let's Go! You were able to print the numbers in your console. But wait... 100 is missing! ๐Ÿ˜ฑ Do you know why? Take a minute to think about why the condition that needs to be met stops at 100. Remember the challenge is to include all the numbers in the range of 1-100 even 100 itself. The key to being a great programmer is paying attention to even the smallest of details.

Hurdle #1 ๐Ÿšง

If you were able to figure it out, great! If you need a hint no worries we can all use a helping hand from time to time. Let's dissect this loop together.

The bug is found in the condition of the for loop n < 100; . 99 is indeed less than 100 which is why it stops at 99. To include 100 in our printed list we need to use the <= operator (pronounced less than or equal to). This allows 100 to be included as a number in the series of conditions that have to be met. Update your condition to be n <= 100; . The results in your console should be as follows.

1
... lots of numbers
99
100

Radical! ๐Ÿค™๐Ÿผ

We now have our for loop iterating all numbers in the range 1-100. Now let's dive back into the body of our for loop to get FizzBuzz working.

Output โžก๏ธ

We already have a variable that contains our number that is printed in the console 'n'. Now we need a new variable that contains no value which we can update freely. We also need to change our console.log() to print our updated variable or a number, in that order. We can structure the body of the "for" loop as follows.

for (let n = 1; n < 100; n++) {
    let output = '';
    console.log(output || n);
}

Now we are getting somewhere! Let's break it down.

Our output variable is pretty straightforward. We can use single quotes to represent an empty string. However, the console.log() command has changed a bit. We now have the double pipe symbol ( | | )separating output and n . This logical operator is referred to in Javascript as "OR".

The order in which we set the variables reading from left to right is of critical importance. Why? We are setting a hierarchy as to what gets logged in the console first. Our structure will result in the output variable being logged first "OR" the variable n if our first condition is not met. If you check your console you will see that we still get numbers in the range of 1-100 being logged. This is exactly what we want, we can keep moving forward.

% operator and the "if" statement

The goal is to have our console print the following.

1
2
Fizz
4
Buzz
...

So how do we get there? Well, know that we will need some basic maths to determine if a number can be divided by 3, 5, or both. What Javascript operator can we use to achieve this? Say hello to the remainder operator, % .

Now don't let its appearance fool you. Its purpose is in the name. At face-value one could assume that the % is used for division. Open your console in your browser or Codepen and type 15 % 2 and press ENTER. The result is 1 and not 7.5, why? Because the remainder operator outputs the remainder of 15 divided by 2 (15 can be divided by 2 a total of 7 times) leaving a remainder of 1. If you type 15 % 3 in the console, the output will be 0 indicating that there is no remainder and the numbers divide exactly. That is the syntax we need. Phew, I hope that was clear.

We need to determine if a number in the range of 1-100 is divisible completely to zero by either 3 or 5. Here we can use a conditional branch called an "if" statement.

if (condition) {
    // do something
}

If statements allow us to perform certain actions based on certain conditions. In our case, we want to print a message that indicates if our requirements have been met. Let us add some more code to the body of our "for" loop.

Fizz โšก๏ธ

Our next step is to check if any number in our range is divisible completely by 3. Remember, our number is being held within the variable n, so we must not forget to check it against that. We also need to update our empty output variable to Fizz if a number in our range meets our first requirement. Therefore our first "if" statement will be structured as follows.

for (let n = 1; n < 100; n++) {
    let output = '';
    if (n % 3 == 0) { output = 'Fizz' };
    console.log(output || n);
}

We are making strides! If you look at your console you will see that the range logged has been updated to:

1
2
Fizz
4
5
Fizz
...

Awesome Sauce! Before we move forward let's examine the "if" statement we just wrote.

We are checking if our condition n (or the number in the range) is divisible by three, but why do we have a == symbol? That is because in Javascript the == comparison operator is meant to test equality and the = operator means an assignment. That is why the output the variable is given the = operator to assign the string of Fizz to it, therefore logging Fizz in the console first because the first condition needed to be met was true.

Note that if a number is not divisible by 3 that same number is logged. This is the result of using the "OR" operator in our console.log command since the if statement was false.

Buzz ๐Ÿ

Do you think you can solve the buzz portion of this exercise on your own? I encourage you to try.

Great effort! Props if you were able to solve it. Again if you were not able to sort it out it is okay. Take a deep breath, crack those knuckles, and let's get our Buzz on.

Since we are trying to determine if a number in our range is divisible by 5 we can simply duplicate our first if statement and change 3 to 5. See the example below.

for (let n = 1; n < 100; n++) {
    let output = '';
    if (n % 3 == 0) { output = 'Fizz' };
    if (n % 5 == 0) { output = 'Buzz' };
    console.log(output || n);
}

Take a peek at your console. The results should look a little something like this.

1
2
Fizz
4
Buzz
...
14
Buzz

Stellar! You can now see in your console that all numbers divisible by 3 are being replaced by Fizz and those that are divisible by 5 are replaced by Buzz .

Hurdle #2 ๐Ÿšง

But hold the phone! If you recall, the final part of the challenge requires us to print FizzBuzz if a number is both divisible by 3 and 5. If you scroll to 15 you will notice that only Buzz is being logged in the console. Why is that? Let's look at both "if" statements in isolation.

if (n % 3 == 0) { output = 'Fizz' };
if (n % 5 == 0) { output = 'Buzz' };

We know by looking at our console that both "if" statements work individually because 3 is replaced by Fizz and 5 is replaced by Buzz . But they don't seem to work together, 15 is replaced by Buzz only. Why? Because JavaScript will take the last condition that is true (from top to bottom) and send only that value to the console for us to read, in our case Buzz. So we need to use syntax to chain both values together to log FizzBuzz when a number is divisible by both 3 and 5. Think you can figure it out? I know you can. Give it a Go!

Hint: The change will occur in the body of the "if" statement (between the { }).

Did you figure it out? Whether you did or not you have reason to rejoice! You are here because you want to learn the fundamentals of programming. You are laying the foundations for a great career, or hobby if that is what you wish to do. Alright, let's wrap up this lesson.

The operator we need to help us cross the finish line is called modify-in-place += (pronounced "plus equals"). What purpose does this operator serve? The += shorthand operator allows us to update the value of a variable and store the new result in the same variable. For example:

let n = 8;
n += 5;
console.log(n); // 13

We can use the += operator to update the value of n which equals 8 to the new value of 13 by using the modify-in-place operator to add 5. The good news is that it also works with strings not just integers. That is exactly the functionality we need.

We need to not only store a new value in our empty variable output but we also need to add on/update the new result of our second if statement if the result is 'truthy.' Here is what it will look like.

for (let n = 1; n < 100; n++) {
    let output = '';
    if (n % 3 == 0) { output += 'Fizz' };
    if (n % 5 == 0) { output += 'Buzz' };
    console.log(output || n);
}

The console will output...

1
2
Fizz
4
Buzz
...
14
FizzBuzz
16

You did it! You have successfully solved the FizzBuzz challenge. Treat yourself to your favorite drink and snack you amazing programmer you ๐Ÿ˜.

In Review

We learned many things about how we can print, analyze, and update data using JavaScript.

"For" loops are a great way to provide a base structure where we can use arguments to define and organize data. We learned about different JavaScript operators: how they function and how we can use them. And we also overcame obstacles by paying attention to the smallest of details and ensuring that we followed the instructions provided which led to your success.

I hope that you were able to gain confidence by solving this challenge. More importantly, I hope that I was able to help you understand some fundamental JavaScript concepts that will be invaluable as you grow as a programmer, one line of code at a time.

  • Your Friendly Neighborhood Chicano ๐ŸŒฎ
ย