js fizzbuzz

JS FizzBuzz

If you are a beginner programmer or preparing for a coding interview, you might have heard of the FizzBuzz problem. In this problem, you have to print numbers from 1 to n. But, if the number is divisible by 3, print "Fizz" instead of the number. If the number is divisible by 5, print "Buzz". If the number is divisible by both 3 and 5, print "FizzBuzz".

Here is one way to solve this problem in JavaScript:


            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);
                    }
                }
            }
            fizzBuzz(15);
        

In this code snippet, we define a function called "fizzBuzz" that takes an argument "n" as the upper limit of the range of numbers. We then use a for loop to iterate through each number from 1 to n. Inside the loop, we use if-else statements to check if the number is divisible by 3 and/or 5 and print "Fizz", "Buzz", or "FizzBuzz" accordingly. If none of these conditions are true, we simply print the number itself.

Another way to solve this problem is by using a switch statement instead of if-else statements. Here is the code for that:


            function fizzBuzz(n) {
                for (let i = 1; i <= n; i++) {
                    switch (true) {
                        case i % 3 === 0 && i % 5 === 0:
                            console.log('FizzBuzz');
                            break;
                        case i % 3 === 0:
                            console.log('Fizz');
                            break;
                        case i % 5 === 0:
                            console.log('Buzz');
                            break;
                        default:
                            console.log(i);
                    }
                }
            }
            fizzBuzz(15);
        

In this code snippet, we use a switch statement to check the conditions for printing "Fizz", "Buzz", or "FizzBuzz". Note that the "true" argument in the switch statement is used to compare the value of each case with the boolean value true.

Both of these solutions work fine for the FizzBuzz problem. However, there are many more ways to solve this problem in JavaScript and other programming languages. The key is to understand the problem and come up with a logical and efficient solution.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe