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>

 
3 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.

© SaintJohnShawn.com