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:
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...
Top comments (3)
Here are some more (I omitted the console logging though, these are just the basic solving function):
and:
Yeah, that's awesome
But unreadable and not easy to extend
`