I\'m currently taking the code academy course on Javascript and I\'m stuck on the FizzBuzz task. I need to count from 1-20 and if the number is divisible by 3 print fizz, by
Here's what made it clear for me, might help :
It's a misinterpretation of what switch (x){}
means.
It doesn't mean : "whenever whatever I put inbetween those brackets is true
, when the value of x
changes."
It means : "whenever x
EQUALS what I put between those brackets"
So, in our case, x
NEVER equals x%3===0
or any of the other cases, that doesn't even mean anything. x
just equals x
all the time. That's why the machine just ignores the instruction. You are not redefining x
with the switch function. And what you put inbetween the brackets describes x
and x
only, not anything related to x
.
In short :
With if/else
you can describe any condition.
With switch
you can only describe the different values taken by the variable x
.
Not to too my own horn but this is much cleaner:
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 1; i <= numbers.length; i++) {
if (i % 15 === 0) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else {
console.log(i);
}
};