-2

I have a simple fizzbuzz here:

var num = 1;

while (num <= 20) {
    switch(true){
        case(num%3 === 0 && num%5 === 0):
            console.log('fizzbuzz');
            break;
        case(num%3 === 0):
            console.log('fizz');
            break;
        case(num%5 === 0):
            console.log('buzz');
            break;
        default:
            console.log(num);
    }
    num++;
}

What is the meaning of the comparison to 0 after the modulus in this line: num%3===0?

Why isn't it just num%3?

Morteza Asadi
  • 1,819
  • 2
  • 22
  • 39
jdev99
  • 95
  • 1
  • 3
  • 11
  • If a number mod 3 is equal to 0...? What don't you understand? – Andrew Li Jan 22 '17 at 04:48
  • I can't find a clear explanation on what that comparison means. Why isn't it just `num%3`? – jdev99 Jan 22 '17 at 04:50
  • 1
    `if(num%3)` and `if(num%3==0)` are exact opposites. The former is true when the number isn't divisible, and the latter is true when it is – Andrew Li Jan 22 '17 at 04:52
  • 1
    Because if `num%3` evaluates to 0, 0 is falsey. Instead you need to check for equality to 0, which would be truthy if divisible. – Andrew Li Jan 22 '17 at 04:52
  • FYI: `num%3 == 0` and `!(num%3)` are equivalent - if that helps – Jaromanda X Jan 22 '17 at 04:56
  • If you need an example: say `x` is 6. `x%3` will be 0. So, if we do `if(x%3)` as you suggested, it would be `if(0)`. Since 0 is falsey, the condition would be false. Instead if we check for equality to 0: `if(x%3==0)` it would evaluate to `if(0==0)` which is true and is correct. – Andrew Li Jan 22 '17 at 04:57
  • Can somebody tell me please what is difference between `==` and `===` – minigeek Jan 22 '17 at 05:05
  • @minigeek http://stackoverflow.com/q/359494/5647260 – Andrew Li Jan 22 '17 at 05:08

2 Answers2

1

If you keep num%3 instead of num%3===0 , Meaning changes completely beacuse to enter into one of the cases it should be divisible by 3 so if it isn't, it will enter to default case as num%3 won't be equal to 0. In short we use % operator to check if it is divisible as if answer comes out be 0 if and only if it is divisible i.e. remainder is 0

minigeek
  • 2,766
  • 1
  • 25
  • 35
0

Suppose num = 1, num%3 is equal to 1. so if you evaluate if(num%3) it will evaluate to true. Whereas if you evaluate if(num%3===0) if will evaluate to false.

Moreover, the === ensures you are not allowing any values in case of different types, however in this case, == and === wont make much difference.

poushy
  • 1,114
  • 11
  • 17