javascriptswitch-statementoperator-keywordnot-operator

usage of !(not) operator in switch case


// 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.


Solution

  • !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`);
    	}
    }