Home > OS >  Condition in switch's case is ignored
Condition in switch's case is ignored

Time:09-17

I'm trying to use a switch statement as follow. But even if status is 301, the case case (status > 200 && status < 400) is ignored and the result is the "default" case. What am I doing wrong? Is it not possibile to use conditions in case statements?

status = 301;
switch (status) {
  case 0:
  case 200:
    console.log('200');
    break;
  case (status > 200 && status < 400):
    console.log('200-400');
    break;
  case 404:
    console.log('404');
    break;
  default:
    console.log('Si è verificato un errore irreversibile.');
}

At the end I solved with a simple if, but I would like to know why this doesn't work.

CodePudding user response:

That's not how switch/case works in JavaScript; you can only match values, not conditions. What happens here is that status > 200 && status < 400 evaluates to true, and true is obviously not the same as 301.

Indeed a simple if/else if/.../else chain is the usual solution here.

CodePudding user response:

This can be achieved by following:

const status = 301;
switch (true) {
  case status === 0:
  case status === 200:
    console.log('200');
    break;
  case (status > 200 && status < 400):
    console.log('200-400');
    break;
  case status === 404:
    console.log('404');
    break;
  default:
    console.log('Si è verificato un errore irreversibile.');
}

But I agree with @Thomas's suggestion, we should prefer using the if/else chain for these kind of problems.

  • Related