Q2: Classic FizzBuzz Implementation

Output numbers from 1 to N, replacing multiples of 3 with 'Fizz', 5 with 'Buzz', and multiples of both with 'FizzBuzz'. Check compound conditions (multiples of 15) before individual factors.

FizzBuzz Loop
function fizzBuzz(n) {
  const result = [];
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) result.push('FizzBuzz');
    else if (i % 3 === 0) result.push('Fizz');
    else if (i % 5 === 0) result.push('Buzz');
    else result.push(i.toString());
  }
  return result;
}

console.log(fizzBuzz(15));
💡 Evaluating i % 15 first prevents multiples of both 3 and 5 from matching the earlier single-factor branches.
Key Takeaways
  • Check for combined conditions (i % 15 === 0) before individual conditions.
  • Demonstrates basic modulo arithmetic and control flow branching.
Knowledge Check

Why must the condition for 15 (or both 3 and 5) be checked first in FizzBuzz?