Overview:
Fizz Buzz is a simple programming task, it basically prints numbers from 1 to a limit, replacing certain numbers with words. Numbers divisible by 3 are replaced with “Fizz”. Numbers divisible by 5 are replaced with “Buzz”. Numbers divisible by both 3 and 5 are replaced with “FizzBuzz”.
Here’s a version with explicit conditions and actions:
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); } }
So i = 1, that’s our initialization for the continuous loop.
% is the modulo operator so if i = 5, we are checking if i is divisible by 5 without remainder.
For example for i = 10, i % 5 is 0, so i % 5 === 0 is true. And something like i = 3 would be false in this example.
If did 3 % 5 alone the remainder would be 3 (since 3 is less than 5, it cannot be divided, so the remainder is 3 itself).
Here’s an even faster method.
for (let i = 1; i <= 100; i++) { let output = ''; if (i % 3 === 0) output += 'Fizz'; if (i % 5 === 0) output += 'Buzz'; console.log(output || i); }
The += operator adds value to a variable, I think of variables as boxes. Putting something (a value) into a box with a name!
output += ‘Fizz’ adds ‘Fizz’ to output.
output = ‘A’; output += ‘B’; results in output being ‘AB’.