FizzBuzz using Javascript

FizzBuzz using Javascript

FizzBuzz is one of the commonly asked tasks during interviews. In FizzBuzz we need to print ‘Fizz’ if the number is divisible by 3. ‘Buzz’ if the number is divisible by 5, if the number is divisible by both 3 and 5 we will print ‘FizzBuzz’. For all other numbers, we need to print the same number.

In this blog, we will solve fizzbuzz tasks with different methods using javascript.

Method 1

// FizzBuzz using Javascript

// Method 1

for (let i = 1; i < 100; i++) {
  i % 3 === 0
    ? i % 5 === 0
      ? console.log("FizzBuzz")
      : console.log("Fizz")
    : i % 5 === 0
    ? console.log("Buzz")
    : console.log(i);
}

// Output
// 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ....

In this way, we are using for loop to iterate from 0 to 100. In each iteration we are using the ternary operator, where first we will check if the number is divided by 3 if the number is divided by 3, then we will check if it is divided by 5, if the number is divided by both 3, and 5 we will print ‘FizzBuzz’, else if the number is only divisible 3 then we print ‘Fizz’, if the number is only divided by 5 then we print ‘Buzz’ for all the other numbers we print number itself

Method 2

// Method 2

for (let i = 1; i < 100; i++) {
  let fizzBuzz = "";
  if (i % 3 === 0) fizzBuzz = fizzBuzz + "Fizz";
  if (i % 5 === 0) fizzBuzz = fizzBuzz + "Buzz";
  console.log(fizzBuzz || i);
}

// Output
// 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ....

In the above code, we are using the if statement to check that the number is divisible by 3 or  5. then we are adding the ‘Fizz’ or ’Buzz’ string to result variable based on the if statement result. If the result variable is empty we will number else, we will print the string in the result.

Leave a Comment

Your email address will not be published. Required fields are marked *