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.
npm run import -- "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();
/**
* 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:
function fizzBuzz() { ... }
: Defines a function named fizzBuzz
that encapsulates the logic.
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.
var buffer = '';
: Initializes an empty string called buffer
to store the output for each number.
if (i % 3 === 0) buffer += 'Fizz';
: Checks if i
is divisible by 3. If so, it appends "Fizz" to the buffer
.
if (i % 5 === 0) buffer += 'Buzz';
: Checks if i
is divisible by 5. If so, it appends "Buzz" to the buffer
.
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
.
console.log(buffer);
: Prints the contents of the buffer
(which will be "Fizz", "Buzz", "FizzBuzz", or the number itself) to the console.
fizzBuzz();
: Calls the fizzBuzz
function to execute the code.
Let me know if you'd like any further clarification!