Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
Condition in switch's case is ignored

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!