Last active
July 27, 2021 12:54
-
-
Save jonurry/c9752926d5ebd2430e9514c56cf4fdb4 to your computer and use it in GitHub Desktop.
2.2 FizzBuzz (Eloquent JavaScript Solutions)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for (var 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); | |
} | |
for (var i = 1; i <= 100; i++) { | |
var output = ""; | |
if (i%3==0) | |
output = "Fizz"; | |
if (i%5==0) | |
output += ("Buzz"); | |
console.log(output || i); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hints
Going over the numbers is clearly a looping job, and selecting what to print is a matter of conditional execution. Remember the trick of using the remainder
(%)
operator for checking whether a number is divisible by another number (has a remainder of zero).In the first version, there are three possible outcomes for every number, so you’ll have to create an
if/else
if/else
chain.The second version of the program has a straightforward solution and a clever one. The simple way is to add another conditional “branch” to precisely test the given condition. For the clever method, build up a string containing the word or words to output, and print either this word or the number if there is no word, potentially by making good use of the
||
operator.