FizzBuzz JavaScript
Tadea Simunovic
Posted on May 2, 2020
One of the classic interview question! I will show you how to resolve it in JavaScript.
Challenge
Write a program that console logs the numbers from 1 to n. For multiples of three print "fizz" instead of the number and for the multiples of five print "buzz". For number which is multiples of both three and five console log "fizzbuzz"
If you know how to calculate a multiple of the number in JavaScript will make this challenge much easier to understand. This example use modulo operator (%). With modulo, we can determine a reminder of the number during division.
Essentially we want to do is take a number that we are trying to use the modulo operator with the number that we are using as the multiple and the real question is whether or not the results to that are equal(===) to zero(0).
Example
12 % 3 === 0 //true
11 % 3 === 0 // false
So in practice, you're going to test for each number from 1 to n (the number that we pass in as an argument) if a given number(n) modulo(%) 3 is equal(===) to zero(0) and if a given number(n) modulo(%) 5 is equal(===) to zero(0).
First, we will set up for loop to iterate from 1
to <= n, and each time we will increment by one(1)
function fizzBuzz(n) {
for (let i = 1; i<= n; i++){}
}
Then we will check if the number is multiple by three and five then we want to console log statements that are required.
function fizzBuzz(n) {
for (let i = 1; i<= n; i++){
if (i % 3 === 0 && i % 5 === 0) {
console.log('fizzbuzz')
}
}
}
Next, we will check if we have a multiple of three and print out 'fizz'
function fizzBuzz(n) {
for (let i = 1; i<= n; i++){
if (i % 3 === 0 && i % 5 === 0) {
console.log('fizzbuzz')
} else if (i % 3 === 0) {
console.log('fizz')
}
}
}
Else, if we have a multiple of five we will print out 'buzz', and if we failed all of this else of statements we will print out a number.
function fizzBuzz(n) {
for (let i = 1; i<= n; i++){
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)
}
}
}
If you run console.log(fizzBuzz(10)) this will be output:
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
I hope this method will be helpful!
Posted on May 2, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.