in this tutorial, We are going to learn How to create ‘fizzbuzz’ program in JavaScript. FizzBuzz is a simple programming problem where you print the numbers from 1 to 100.
However, instead of printing the number for multiples of 3, print “Fizz,” and for multiples of 5, print “Buzz.” If a number is a multiple of both 3 and 5, output “FizzBuzz.”
Sample Example of FizzBuzz in JavaScript
Let’s create a sample javascript code to print numbers in fizzbuzz manner, the rules are:
- If a number is divisible by 3, print “Fizz.”
- If a number is divisible by 5, print “Buzz.”
- If a number is divisible by both 3 and 5, print “FizzBuzz.”
- Otherwise, print the number itself.
Using Simple for loop
We’ll generate fizzbuzz using simple for loop in javascript.
function generateFizzBuzz() { for (let i = 1; i <= 100; i++) { // Check for multiples 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); } } }
in the above code, we have iterates from 1 to 100, and based on the conditions, it prints “Fizz,” “Buzz,” “FizzBuzz,” or the current number. You can also create a parametrized function.
Parametrized Method
Let’s create a method and pass the number as a parameter, that will return a response based on the passed number.
function generateFizzBuzz(number) { if (number % 3 === 0 && number % 5 === 0) { return "FizzBuzz"; } else if (number % 3 === 0) { return "Fizz"; } else if (number % 5 === 0) { return "Buzz"; } else { return number; } } for (let i = 1; i <= 100; i++) { console.log(generateFizzBuzz(i)); }
Using Ternary Operator
You can also create fizzBuzz using ternary operator as well in javascript:
function generateFizzBuzz(number) { for (let i = 1; i <= 100; i++) { console.log( i % 3 === 0 && i % 5 === 0 ? "FizzBuzz" : i % 3 === 0 ? "Fizz" : i % 5 === 0 ? "Buzz" : i ); } }
Conclusion
We’ve covered a number of methods for developing JavaScript FizzBuzz programs. It helps developers to create different approaches to problem-solving. This exercise helps in interview preparation for coding-related tasks.