JS CodeLab
algorithmsbeginner

JavaScript FizzBuzz Interview Algorithm Explained

•
Updated

Direct Answer & Overview

FizzBuzz is a classic coding interview problem that iterates through integers, printing Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both 3 and 5 (15). It tests modulo arithmetic and correct evaluation ordering.

#fizzbuzz#algorithms#modulo#interview-questions

JavaScript Source Code

example.js
for (let i = 1; i <= 20; i++) {
  if (i % 15 === 0) {
    console.log("FizzBuzz");
  } else if (i % 3 === 0) {
    console.log("Fizz");
  } else if (i % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
}

How does this JavaScript code work?

FizzBuzz evaluates numbers from 1 to N using the modulo operator (`%`). A number is evenly divisible by another if `number % divisor === 0`. Because numbers divisible by both 3 and 5 are multiples of 15, the condition `i % 15 === 0` must be tested first before checking divisibility by 3 or 5 individually; otherwise, multiples of 15 would be prematurely intercepted by the first branch.

What is the expected terminal output?

Executing this code in JS CodeLab produces the following stdout sequence in the developer console:

Console Standard Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

Common mistakes to avoid

  • !Testing for 3 or 5 before testing for 15, which prevents FizzBuzz from ever being reached.
  • !Using separate independent if statements rather than an if...else if ladder, causing duplicate logs.
  • !Off-by-one errors in loop boundaries (e.g. i < 20 instead of i <= 20).
  • !Using loose equality (== 0) instead of strict comparison (=== 0).

Frequently Asked Questions

Why must i % 15 === 0 be checked first in FizzBuzz?

Because any multiple of 15 is also divisible by 3 and 5. If you checked i % 3 === 0 first, 15 would trigger 'Fizz' and never evaluate the 15 branch.

Can FizzBuzz be solved without checking 15 explicitly?

Yes. You can build the string dynamically: let str = ''; if (i % 3 === 0) str += 'Fizz'; if (i % 5 === 0) str += 'Buzz'; console.log(str || i);

What is the time complexity of the FizzBuzz algorithm?

The algorithm runs in O(n) linear time, evaluating each integer from 1 to n with constant-time arithmetic operations.