Cant i do this like that?


#1

var num=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
console.log (num);
switch (num){
case div3 :
if (num%3===0){
console.log("fizz");
break;

        case div5 :
            if (num%5===0){
                console.log("buzz");
                break;

            case both:
                if (num%3===0 && num%5===0){
                    console.log ("FizzBuzz");
                    break;

                    default:
                    console.log(num);
                };

#2

hem no oO
first if you want to create an array :
either var num= array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
or var num= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 ];
(there are other way but those 2 are the closest to your code)

then I m not sure you can call an array as a switch condition...
but you can definitely not say "case div3", that means nothing for the computer.
if I was you I will use if/else if/else if/else statment instead of switch. And use a for loop to check every number of your array.


#3

I think that's what you're trying to do :

for (var i=0; i < 20; i++) {
if (((num[i]%3)===0) && ((num[i]%5)===0)) {
console.log("FizzBuzz");
} else if ((num[i]%3)===0) {
console.log("Fizz");
} else if ((num[i]%5)===0) {
console.log("Buzz");
} else {
console.log(num[i]);
}
};


I can’t figure out what’s wrong?
#4

The exercise does ask us to use an if/else if/else statement, so we should complete the exercise on spec. But, afterward, go to town experimenting.

We need to understand that case ___: is not a label, but an expression.

for (var s, i = 1; i < 21; i++) {
    s = "";
    switch (0) {
    case i % 15: s = "FizzBuzz"; break;
    case i % 3:  s = "Fizz"; break;
    case i % 5:  s = "Buzz"; break;
    default:     s = i;
    }
    console.log(s);
}

The first case to match the switch parameter gets the branch.


#5

can you explain "switch (0)" ?


#6

A switch is like an identity operation, A === B, which can also be written, B === A because of the identity relationship.

switch (A) {
case b: break;
case c: break;
case d: break;
default: //
}

If any expression, b, c or d is equal to A, the expressions match and control flows through that branch.

In the above, switch(0), the first expression to equal zero gets the branch. Bear in mind that an expression always yields a value.