CAVEAT: This article isn't exactly meant to be taken as coding law. This is simply my understanding and method of coding if/else statements! Find your own method or copy mine-- if you think it applies to your solution, then try it!
This article also assumes you already know how to write for-loops and if/else statements in JavaScript.
- EDIT 1/29/2020 at 4:35 PM: fixed the formatting of the code blocks and made it more readable*
In some iteration of the infamous "FizzBuzz" question, you will be asked to:
- Write a JavaScript application that logs all numbers from 1 - 100.
- If a number is divisible by 3 log "Fizz" instead of the number.
- If a number is divisible by 5 log "Buzz" instead of the number.
- If a number is divisible by 3 and 5 log "FizzBuzz" instead of the number.
Look at all those requirements. If you're like me -- someone who isn't exactly fond of math -- you'd either attempt to crunch numbers or walk away (and deal with it later. Maybe.)
But, honestly, the solution is simple and sweet:
Presenting: the modulo (%)
What does it do? It gives you the remainder--and ONLY the remainder.
Since we're only finding numbers divisible by 3, 5, and both 3 and 5, the remainder must equal ZERO (0).
So at first, I wrote the solution like this:
for (i=0; i < 100; i++){
if((i % 3) === 0){
console.log("Fizz");
}
else if((i % 5) === 0){
console.log("Buzz");
}
else if((i % 3) === 0 && (i % 5) === 0){
console.log("FizzBuzz");
}
else {
console.log(i);
}
}
Success! Fizz's and Buzz's were being logged.
But wait-- not FizzBuzz's?
I realized my mistake and forgot:
Code is executed from the top-down.
So I fixed it:
for (i=0; i < 100; i++){
if((i % 3) === 0 && (i % 5) === 0){
console.log("FizzBuzz");
}
else if((i % 5) === 0){
console.log("Buzz");
}
else if((i % 3) === 0){
console.log("Fizz");
}
else {
console.log(i);
}
}
This is where specificity comes in!
We have 3 requirements, with one involving numbers that have been previously mentioned: 3 and 5.
Since printing "FizzBuzz" has more requirements/rules, I moved it to the top to be executed first.
My mistake was that I wrote the code in the order of instruction.
Bonus: We can simplify the solution a bit more by changing the first if/else condition:
- EDIT 1/29/2020 at 4:40 PM: DO NOT DO THIS. THINK OF SCALABILITY.
if((i % 15) === 0){
console.log("FizzBuzz");
}
Remember: this still has to execute at the top. We're looking for numbers that divide by 3 and 5.
Why 15? Typically, when dealing with division, one would think of it's opposite for the "reverse" solution: multiplication.
That's it!! Hope you all found this useful! Feedback and constructive critique are always welcome in the comments or my DMs. :)
Question for the comments:
What was the first programming problem you conquered, what language, and how did it feel when all the information finally clicked?
Thanks for reading! If you'd like to keep in touch, please don't hesitate to follow me here and add me on Twitter (@catcarbn) and LinkedIn!