DEV Community

Ben Haugen
Ben Haugen

Posted on

Solving FizzBuzz with JavaScript

Welcome back. Let's take another look at a commonly asked coding question that can be encountered in very junior interviews. If you have spent more than a few weeks coding, you have probably run into the legendary "FizzBuzz" problem. Your task, should you choose to accept it, is to write a program that prints the numbers from 1 to whatever number you are given. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

The goal of this exercise is to prove that you know how to write a simple for loop that prints out the appropriate numbers or words when given a specific number. Let's think about a hypothetical. If we were given the number 10, you would expect this function to print out these numbers:
*1
*2
*Fizz
*4
*Buzz
*Fizz
*7
*8
*Fizz
*Buzz

Notice we never printed "FizzBuzz" because we never ran into a number that was divisible by both 3 and 5. Let's think about what the first number would be that actually is a multiple of both. That number would be 15. We can use this knowledge when writing our function.

We want to start our conditional statements with this information because if it is written after the first two if statements, then instead of printing "FizzBuzz" for the number 15, it will print out "Fizz" because it met that condition first.

A few things to keep in mind on the for loop:

  • Because we want to print out 1 first, make sure to set i = 1
  • Because we want to go up UNTIL the given number, make sure to keep the loop running when i is less then AND until it is equal to the given number

Ok, the rest is pretty simple. Write your for loop and include those three if statements. Make sure to have one final condition that prints out the number when none of the conditions above are met. Here is the solution below:

Top comments (0)