JavaScript Challenge (Part 1)
Today, we will be covering the classic FizzBuzz question!
Here are the directions:
Write a program that console logs the numbers from 1 to n. 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".
A few things to keep in mind as we tackle this question. The first thing to keep in mind is that the key to solving this challenge is recognizing exactly how the modulo operator works.
The other thing to keep in mind is that as we are iterating through our list of numbers, we want to print out the number, “fizz”, “buzz”, or “fizzbuzz”. So for one particular number, we print out only one thing, we don’t print out like three and “fizz”, we only print out “fizz”.
With that out of the way, let’s start figuring out the solution.
Step one is to make sure that we can iterate from 1 to n inside of the function. So, let’s set up a loop inside of it to iterate from one to end:
function fizzBuzz(n) {
for (let i = 1; i <= n; i++) {}}
Next thing we want to do here is check to see if the number is a multiple of both 3 and 5:
function fizzBuzz(n) {
for (let i = 1; i <= n; i++) {
// Is the number a multiple of 3 and 5?
if (i % 3 === 0 && i % 5 === 0){
console.log('fizzbuzz');
}
}
}
Now, the thing to recognize next is that we don’t want to set up another separate if statement. So if we meet the about situation, then the console.log is the only code that executes.
And so to make sure that’s the case, rather than writing out a bunch of separate if statements, we’ll write out a bunch of ELSE IF statements.
function fizzBuzz(n) {
for (let i = 1; i <= n; i++) {
// Is the number a multiple of 3 and 5?
if (i % 3 === 0 && i % 5 === 0){
console.log('fizzbuzz');
} else if (i % 3 === 0) {
console.log('fizz');
} else if (i % 5 === 0) {
console.log('buzz');
} else {
console.log(i);
}
}
}
So this right here is the classic implementation of FizzBuzz.