Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1618 Can swtch statements in JavaScript apply to a range of values?

You are here: irt.org | FAQ | JavaScript | General | Q1618 [ previous next ]

Yes, just omit the break statement and the case statements will all invoke the code up to the next break statement. In the following example, the text 1-5 will be output for any number from 1 to 5, and likewise for 6-10:

<script language="JavaScript"><!--
function testFunction(i) {
  switch (i) {
    case 1 :
    case 2 :
    case 3 :
    case 4 :
    case 5 :  document.write('1-5<br>');
      break;
    case 6 :
    case 7 :
    case 8 :
    case 9 :
    case 10 :  document.write('6-10<br>');
      break;
    default :
      document.write('Sorry, ...<br>');
  }
}

for (var i=0; i<15; i++) {
  testFunction(i);
}
//--></script>

Alex Vincent writes:

Found a better way to make switch statements apply for ranges.

<script language="JavaScript"><!--
var x = 2

switch (true) {
  case (1 > x):
    alert("1 > x")
    break;

  case ((1 < x)&&(x < 3)):
    alert("Pass")
    break;

  case (x > 3):
    alert("x > 3")
    break;

  default:
    alert("Oh boy")
}
//--></script>

Feedback on 'Q1618 Can swtch statements in JavaScript apply to a range of values?'

©2018 Martin Webb