magnify

Javascript: Example switch statement using a range of values.

Published on 2007-05-24 by in Development

Here is a sample snippet which should give a good example of how to use a range of values inside of a javascript switch statement:

<script language="JavaScript" type="text/javascript">
<!--
	function GetText(value)
	{
		var result;

		switch (true)
		{
			case (value == 0):
				result = "Equals Zero.";
				break;

			case ((value >= 1) && (value <= 25)):
				result = "Between 1 and 25.";
				break;

			case ((value >= 26) && (value <= 50)):
				result = "Between 26 and 50.";
				break;

			case ((value >= 51) && (value <= 75)):
				result = "Between 51 and 75.";
				break;

			case ((value >= 76) && (value <= 100)):
				result = "Between 76 and 100.";
				break;

			default:
				result = "Not found in the range.";
				break;
		}

		return result;
	}

//-->
</script>

 
5 Comments  comments 
  • Enrique

    That was so helpful, thanks for the explanation

  • mprototype

    agreed. Couldn’t have asked for it to be more simplified. Thx for the syntax

  • GlassLinux

    Thank you so freaking much finally someone that explains it without the default case1, case2 bs.

  • Cory Gross

    This isn’t really the same as a true switch…. in a switch statement there is a single evaluation and a table lookup directly to the correct case. Here you go through the entire switch statement and evaluate each case one after the other.

    A more efficient way to do this, yet much more tedious, would be something like:

    switch(value) {
    case 0:
    case 1:
    case 2:
    case 3: // range 0-3
    // do something for 0-3
    break;
    case 6:
    case 7:
    case 9: // range 6-9
    // do something for 6-9
    break;
    default: // everything else
    break;
    }

  • http://twitter.com/Carfolio Carfolio.com

    Assuming your value is an integer, then the secondary clauses are redundant as the switch will fall through to the next test in each (ahem) case. Just be sure you keep the cases in numerical order though. If value is not an integer though, then values between each case test are not going to be caught, or rather, will be caught by your default, which isn’t what you intended, I think.