fizz buzz | | Cell 1 | Search

This JavaScript code implements the FizzBuzz challenge, which prints "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for multiples of both, and the number itself otherwise, from 1 to 100.

Run example

npm run import -- "http://wiki.c2.com/FizzBuzzTest"

http://wiki.c2.com/FizzBuzzTest

function fizzBuzz() {
    for(var i = 1; i <= 100; i++) {
        var buffer = '';
        if(i % 3 === 0)
            buffer += 'Fizz';
        if(i % 5 === 0)
            buffer += 'Buzz';
        if(buffer.length === 0)
            buffer += i;
        console.log(buffer);
    }
}

fizzBuzz();

What the code could have been:

/**
 * Prints the FizzBuzz sequence up to 100.
 * 
 * The FizzBuzz sequence is a series of numbers where each number is replaced by:
 * - "Fizz" if it's a multiple of 3
 * - "Buzz" if it's a multiple of 5
 * - The number itself if it's not a multiple of either 3 or 5
 */
function fizzBuzz() {
    // Use a more efficient approach by directly generating the output string
    for (let i = 1; i <= 100; i++) {
        const output = getFizzBuzzString(i);
        console.log(output);
    }
}

/**
 * Returns the FizzBuzz string for a given number.
 * 
 * @param {number} num The number to generate the FizzBuzz string for
 * @returns {string} The FizzBuzz string for the given number
 */
function getFizzBuzzString(num) {
    // Use a more efficient approach by checking the conditions only once
    let output = '';
    if (num % 3 === 0) output += 'Fizz'; // Check for Fizz first to avoid adding extra strings
    if (num % 5 === 0) output += 'Buzz';
    if (output === '') output = num.toString(); // Use toString() for consistency
    return output;
}

fizzBuzz();

This JavaScript code implements the classic "FizzBuzz" programming challenge.

Here's a breakdown:

  1. function fizzBuzz() { ... }: Defines a function named fizzBuzz that encapsulates the logic.

  2. for (var i = 1; i <= 100; i++) { ... }: A for loop iterates from 1 to 100 (inclusive). In each iteration, the variable i represents the current number.

  3. var buffer = '';: Initializes an empty string called buffer to store the output for each number.

  4. if (i % 3 === 0) buffer += 'Fizz';: Checks if i is divisible by 3. If so, it appends "Fizz" to the buffer.

  5. if (i % 5 === 0) buffer += 'Buzz';: Checks if i is divisible by 5. If so, it appends "Buzz" to the buffer.

  6. if (buffer.length === 0) buffer += i;: If neither "Fizz" nor "Buzz" was added, it means the number is not divisible by 3 or 5, so it appends the number i itself to the buffer.

  7. console.log(buffer);: Prints the contents of the buffer (which will be "Fizz", "Buzz", "FizzBuzz", or the number itself) to the console.

  8. fizzBuzz();: Calls the fizzBuzz function to execute the code.

Let me know if you'd like any further clarification!