In this tutorial I’ll show you two possible solution for the popular FizzBuzz task. The first one is ging to be an easier one, while the other will be slightly more complicated.
FizzBuzz is a popular programming task that you can come accross during a job interview. You are required to print out numbers from 1 and if the number is divisible by three, print out “fizz”, if the number is divisible by five, print out “buzz”, if it is divisible by three and five, print “FizzBuzz”, otherwise print the number.
So let’s see how we can do it.
FizzBuzz – Solution 1
function fizzBuzzV1(number) {
let i;
for(i = 1; i <= number; i++) {
if(i % 15 == 0) {
console.log("FizzBuzz")
} else if(i % 3 == 0) {
console.log("Fizz")
} else if(i % 5 == 0) {
console.log("Buzz")
} else {
console.log(i)
}
}
}
fizzBuzzV1(15)
First, we create a function called “fizzBuzzV1”. It takes one parameter, the “number”.
Then we declare a looping variable called “i”. Then we create a for loop that will start counting the numbers from 1 until it is less than or equal to the number we provide when calling this function.
Inside the for loop we use “if else if” statements to check if the number in the current iteration is divisible by 3, 5 or both. For this we use the modulus operator.
FizzBuzz – Solution 2
function fizzBuzzV2(number) {
let i;
for(i = 1; i <= number; i++) {
let word = '';
if(i % 3 === 0) {
word += 'Fizz';
}
if(i % 5 === 0) {
word += 'Buzz';
}
if(word == '') {
console.log(i);
} else {
console.log(word);
}
}
}
fizzBuzzV2(15);
Here we start like in the first one. We create a function, then declare a looping variable. the conditions of the for loop is again the same as in the first one. How we check the numbers is a little bit different.
We declare a new variable called “word” and set it to an empty string. Then we have three if statements.
In the first if statement we check if the value of “i” is divisible by 3. If it is, we use the addition assignment operator to add the word “fizz”
Here we basically say:
word = word + "Fizz"
Then we do the same, but here we check if the value of “i” is divisible by 5. If it is, we add the word “Buzz”.
We don’t have to check separately if a number is divisible by both 3 and 5, because if it is the variable “word” already has the two words combined. So it will print “FizzBuzz”.
Lastly, we have to check if the number is not divisible by neither 3 nor 5.
Leave a reply