There's a famous little programming challenge called FizzBuzz. It's been used for years in job interviews, because it's a quick way to check that someone understands loops, conditions, and the remainder operator. Here are the rules:
Print the numbers from 1 to 15. But for multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz". And for numbers that are multiples of both 3 and 5, print "FizzBuzz".
Have a go yourself before reading our solution! Seriously, cover the page. We'll wait.
...Okay, here's one way to do it:
for (let i = 1; i <= 15; 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);
}
}
It prints
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
The key insight is that the "both" check has to come first. Remember the "order matters" lesson from Grade 4? If we checked i % 3 === 0 first, then 15 would print "Fizz" and stop, never reaching "FizzBuzz."
You just solved a real job interview question. In Grade 5. Not bad!