Step by step JavaScript interview challenge and solution – Fizz Buzz
When going to an interview for a developer job, you have to expect being put to the test. Fizz Buzz is the most classic challenge which has been used for decades and is the most likely challenge to show up during an interview.
In this article I will give you a step by step solution, so you can ace that interview!
What is Fizz Buzz?
FizzBuzz is a very simple programming exercise that goes like this:
Write a program that prints the numbers from 1 to 100. If it’s a multiple of 3, it should print “Fizz”. If it’s a multiple of 5, it should print “Buzz”. If it’s a multiple of 3 and 5, it should print “Fizz Buzz”.
Steps for solving this challenge might be as follows:
- Loop through the numbers from 1 to 100 and print out the current number.
- However, if the number is dividable by 3, you write out Fizz.
- If the number is dividable by 5, you write out Buzz.
- If the number is dividable by 3 and 5, you write out Fizz Buzz.
So the finished output should look something like this:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 Fizz Buzz
Pretty simple right? I suggest you try this exercise on your own. If you get stuck, feel free to look it up online (But do not google “Fizz Buzz solution”. That’s cheating! :)). Some of you might struggle to find out if a number is dividable by another number. A hint can be found here.
Read further for a suggested solution.
Step 1 – The loop
A good first step is to write the loop from 1 to 100 and just print out the numbers. Don’t worry about Fizzes and Buzzes for now. We will deal with that later.
for (var i = 1; i < 100; i++) { console.log(i); }
The resulting output is this: (I will just show the first 10, but you get the idea)
1 2 3 4 5 6 7 8 9 10
Wow! You just made a for-loop! The recruiters are so impressed, they almost fall out of there chair! Kidding aside though. There are surprisingly many developers who are struggling with the simplest problems. They might be nervous about the interview setting, or they might simply not been practicing enough.
So what have we done so far?
The for-loop works like this. The first part:
var i = 1;
Here you just initialize a variable and assign it to 1. This is done only once at the beginning of the loop.
The second part:
i <= 100;
Here we check if the variable is equal or less than 100. If that is true, we will run the code in the loop.
After the loop is finished, we will run the third and last part:
i++
Here we just increment the variable by one. Then we will check if the variable still is less or equal than 100, and the code will continue the loop until the variable is more than 100. Then the condition is false, in other words, it is not less or equal than 100 and you will break out of the loop.
Inside the loop we have just one line of code:
console.log(i);
This just writes out what “i” is in the console if you just run it with Node in a terminal. Or if you run it in the browser, you can see the result in the console window of the developer tools.
This is just a simple way to display the results.
Step 2 – write out Fizz
The next step is to write out “Fizz” whenever the number is dividable by three.
We can do this by using the remainder operator “%”. So if we have 6 % 3, it will take 6 divided by 3, and find the remainder. In this case, it is 0.
Let’s see how we can implement this by updating the solution:
for (var i = 1; i <= 100; i++) { if (i % 3 === 0) { console.log("Fizz"); } else { console.log(i); } }
Here we have added an if-statement which checks if the number in the loop is dividable to 3 with the remainder operator.
Also, notice we have added an else-statement after the end of the if-statement. This is important to remember, or you will get the result “Fizz” and 3 in the same loop iteration. Remember that we should only print out Fizz if it is dividable to 3, not the actual number.
Step 3 – write out Buzz
Now let us write out Buzz. This is when the number is dividable by 5. This is easy. We use the same technique as the last step. Only we use the remainder operator on 5 instead of 3.
Let’s see how this will look:
for (var i = 1; i <= 100; i++) { if (i % 3 === 0) { console.log("Fizz"); } else if (i % 5 === 0) { console.log("Buzz"); } else { console.log(i); } }
So here we have added an else-if-statement. So the code reads like this:
- If the number is dividable by 3, we print out “Fizz”.
- Else, if the number is dividable by 5, we print out “Buzz”.
- If none of those two conditions are met, we will enter the last else block and print out the actual number.
Step 4 – write out Fizz Buzz
The last step is to print out “Fizz Buzz” if the number is dividable by 3 And 5.
Let’s update the code to the final result:
for (var i = 1; i <= 100; i++) { if (i % 3 === 0 && i % 5 === 0) { console.log("Fizz Buzz"); } else if (i % 3 === 0) { console.log("Fizz"); } else if (i % 5 === 0) { console.log("Buzz"); } else { console.log(i); } }
We use two conditions in the if-statement to determine if it should print “Fizz Buzz”. We use a double ampersand, which means both conditions must be true. Also, here it is important to insert the else in the next statement.
So here we have it. If we run this code, we will get the following output like expected (first 15 numbers):
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 Fizz Buzz
This seems about right. You have successfully solved the classical Fizz Buzz challenge!
Improvements
If you are having a corporate job as a developer, most likely you will be working in a team. This means people will read and write your code and vice versa.
It is therefore very important to write code that is easy to understand. To be honest, this is also important if you are the only developer on an application. You might have experienced this when you have written some code, and you have left it a couple of months. If you then come back to it, you have to struggle to figure out what the code does.
What you want to do is to refactor the code, which means renaming and restructuring the code, so it is more readable to humans. There are tons of ways to do this. Here is a suggestion of how you can structure the code differently:
function calculateFizzBuzz() { var MAX_NUMBER = 100; for (var numberToCheck = 1; numberToCheck <= MAX_NUMBER; numberToCheck++) { if (isDividableBy3(numberToCheck) && isDividableBy5(numberToCheck)) { printToScreen("Fizz Buzz"); } else if (isDividableBy3(numberToCheck)) { printToScreen("Fizz"); } else if (isDividableBy5(numberToCheck)) { printToScreen("Buzz"); } else { printToScreen(numberToCheck); } } } function isDividableBy3(numberToCheck) { return numberToCheck % 3 === 0; } function isDividableBy5(numberToCheck) { return numberToCheck % 5 === 0; } function printToScreen(printValue) { console.log(printValue); } calculateFizzBuzz();
Here I have divided the code into smaller functions. As you might notice if you read the code, it is more understandable.
First I have a master function, which runs the whole Fizz Buzz code.
I have defined a variable “MAX_NUMBER” to 100. Previously the 100 value was a “magic” number, but by assigning it to a named variable, the code is better described. You might be wondering why I put the variable name all in caps. This is just a naming standard if it is a constant, in other words, the variable will never change.
I have also created two functions for checking if the number is dividable by 3 or 5. This makes reading the code more like English. Also, the function “printToScreen” was just created to be more readable.
You may notice that this solution got longer variable names and more lines of code than the original solution.
Are more lines of code bad for performance?
In a word, no. Long variable names and more lines make microscopic differences which have no noticeable impact on your app.
Example of things that are costly in your code are things like heavy calculation or getting data from files and databases.
Why do recruiters use a coding challenge like Fizz Buzz in interviews?
The reason to use these kinds of challenges is to see if the candidate has done any practical programming in the recent years.
This a very simple challenge, and is a fast way to screen out those who can’t code. So in other words, if you are unable to solve these kinds of basic challenges, you probably won’t get the job.
Interviews are a very stressful situation and the recruiters usually want to start out with something easy. This shows them that the candidate can handle simple tasks under stress, and as long as they pass the first challenge, they are more confident and relaxed to tackle harder challenges.
Conclusion
When applying for a job, there is almost guaranteed that you will face at least an easy challenge like Fizz Buzz. If you are confident going into the interview knowing you can handle any simple challenges, you will be more relaxed overall.
It is therefore very important that you are prepared. I have given you a solution to solve this particular challenge, but you might get another similar challenge.
To practice these sort of challenges, I would recommend signing up to Edabit. It is totally free, and they have more than enough challenges for you to solve. You can write the code directly in the browser, or you can do it like me and write the code in an IDE like Visual Studio Code and copy/paste it into the browser.
You should set off 10-15 minutes every day and do as many challenges you can finish in that time. If you do that, you will be comfortable with those kinds of challenges in a short amount of time.
It’s truly a nice and helpful piece of info.
I’m satisfied that you just shared this useful information with
us. Please stay us informed like this. Thanks for sharing.