This content originally appeared on DEV Community and was authored by Rithik Samanthula
Hey There!
When I was a kid everyone used to play a game called FizzBuzz. I personally loved playing it with my family members.
Anyways, the game goes like this:
1, 2, fizz, 4, Buzz, fizz, 7, 8, fizz, Buzz
For every multiple of 3. you have to replace it with Fizz.
For every multiple of 5, you have to replace it with Buzz.
Now, during web development interviews, the most common question that interviewers ask are: "Write a program in JavaScript that prints the order of FizzBuzz"
As you can see in this donut chart, 90% of the interviewees fail and 10% pass to do so.
Don't want to be part of that 90%?
Today, we will be learning how to write a program that prints FizzBuzz in JavaScript.
First, create a variable called output, and set it to an empty array:
var output = [];
Then, create a function called fizzBuzz and create a for if condition wrapped around a for loop:
var output = [];
function fizzBuzz() {
for() {
if () {
}
Then type this in the for and if commands:
function fizzBuzz() {
for(var count = 1; count < 101; count++) {
if (count % 3 === 0 && count % 5 === 0) {
output.push("FizzBuzz");
}
After that, use else if
statements. Like this:
else if (count % 3 === 0) {
output.push("Fizz");
}
else if (count % 5 === 0) {
output.push("Buzz")
}
else {
output.push(count);
}
These else and else if should still be in the fizzbuzz function.
Finally, console log the output by using:
console.log(output);
}
This is how the final code should look like:
var output = [];
function fizzBuzz() {
for(var count = 1; count < 101; count++) {
if (count % 3 === 0 && count % 5 === 0) {
output.push("FizzBuzz");
}
else if (count % 3 === 0) {
output.push("Fizz");
}
else if (count % 5 === 0) {
output.push("Buzz")
}
else {
output.push(count);
}
}
console.log(output);
}
Test the output by running the JS Code in the console.
To run the code, paste the code and hit enter. Then, use fizzBuzz();
If you get an output like this, then HOORAY! It works.
Now, you've learned how to solve the FizzBuzz challenge and you will not be part of the 90% anymore!
Bonus
Here is an alternate and easier way to solve the FizzBuzz challenge:
Thanks for reading and remember...
Keep Coding Y'All ???
This content originally appeared on DEV Community and was authored by Rithik Samanthula

Rithik Samanthula | Sciencx (2021-04-09T11:59:31+00:00) Solving the FizzBuzz Interview Question with JavaScript. Retrieved from https://www.scien.cx/2021/04/09/solving-the-fizzbuzz-interview-question-with-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.