usage of !(not) operator in switch case

2.2k views Asked by At

// checking whether a number is a multiple of 3 or not 
for (let number = 1; number <= 100; number++) {
  switch (number % 3) {
    case !0: // Here I have used !(not) but it's not helping, I only want to know why '!' is not helping           
      console.log(`${number} is not multiple of 3`);
      break;

    default:
      console.log(`${number} is multiple of 3`)
  }
}

Here the 1st case is not working. Code execution has no problems but the 1st case is not helping at all. The complete flow is going to the 'default:' code block only. Whenever the remainder is not equal to 0, the 1st case's code block should be executed, but it's always going to the default code block.

4

There are 4 answers

1
Hao Wu On BEST ANSWER

!0 evals to true, which is not equals to 1 or 2.

Consider writing it in this way:

for (let number = 1; number <= 100; number++) {
 switch (number % 3) {
  case 0:
   console.log(`${number} is multiple of 3`)
   break;
  default:
   console.log(`${number} is not multiple of 3`);
 }
}

2
Nicolas On

In JS, 0 is considered falsy that's why !0 will equals true ( not falsy ).

As for your switch, you could reverse your it and use a true as the switch values. The cases would then have the expression to check

for (let number = 1; number <= 100 ;number++ ) {
   switch (true) {
     case number % 3:        
         console.log(`${number} is not multiple of 3`); 
     break;

     default:
         console.log(`${number} is multiple of 3`)
  }
}
2
Al Hill On

You can't do it in this way because !0 is always true in JavaScript so the loop always enters in the first case

Try it in this way

for (let number = 1; number <= 100 ;number++ ) {
  if(number % 3){
    console.log(`${number} is not multiple of 3`); 
  }
  else{
    console.log(`${number} is multiple of 3`); 
  }
}
0
Elias Soares On

The switch statement receives values on case statements, not expressions like the if. So, when js run your code, it will evaluate !0 to true (inverse of a falsy value is true).

You must replace your switch by if and elses:

for (let number = 1; number <= 100 ;number++ ) {
    if ((number % 3) !== 0) {
         console.log(`${number} is not multiple of 3`); 
    } else {
         console.log(`${number} is multiple of 3`)
    }
}

But you can still use a switch case statement if you invert the logic:

for (let number = 1; number <= 100 ;number++ ) {
   switch (number % 3) {
     case 0:      
         console.log(`${number} is multiple of 3`)
     break;
     default:
         console.log(`${number} is not multiple of 3`); 
  }
}

But really makes no sense using a switch case in this situation since an if-else is much simpler and easier to read.