Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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

irt.org | Knowledge Base | JavaScript | General | Q1618 [ previous next ]

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

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?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.