JavaScript -  FizzBuzz Solutions

JavaScript - FizzBuzz Solutions

What is FizzBuzz?

FizzBuzz is a programming problem that involves iterating through a series of numbers and replacing certain values with the words "Fizz" or "Buzz" based on whether they are divisible by 3 or 5, respectively. The goal is to print out the resulting sequence of numbers and words.

FizzBuzz Solution

For Loop & If Else

for (let i = 1; i <= 100; 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);
  }
}

The implementation I provided uses a for loop to iterate over the numbers from 1 to 100. For each number, it checks whether the number is divisible by 3, 5, or both using the modulo operator (%). If the number is divisible by 3 and 5, it prints "FizzBuzz". If it is only divisible by 3, it prints "Fizz". If it is only divisible by 5, it prints "Buzz". If it is not divisible by either 3 or 5, it prints the number itself.

This approach is a simple & straightforward way to solve the FizzBuzz problem. It uses basic programming concepts such as loops, conditionals, and modulo arithmetic. The implementation is also easy to read and understand, making it a good choice for a coding interview where the goal is to demonstrate your programming skills and problem-solving ability.

Another possible improvement could be to use a ternary condition instead of a series of if/else statements. This could make the code more concise and easier to read, especially if there are multiple conditions to check.

For example: For Loop & Ternary Operator

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

For each number, it checks if it is divisible by 3 and/or 5 using the modulo operator (%). If the number is divisible by 3, it adds the string 'Fizz' to the output. If the number is divisible by 5, it adds the string 'Buzz' to the output. If the number is not divisible by 3 or 5, it outputs the number itself.

The code then uses the logical OR operator (||) to check if the output string is empty. If it is empty, meaning the number is not divisible by 3 or 5, it outputs the number itself.

Finally, the program logs the output to the console for each iteration of the loop.