Javascript TUTORIAL


Switch statement type matching


If the parameter of the switch statement is string and the parameter of the case is integer, they do not match. As an example consider the following code

  1. <html>
  2. <body>
  3. <script type="text/javascript">
  4. <!--
  5. /*
  6. ********************************************************
  7. ReferenceDesigner.com
  8. Example switch statement type matching
  9. ********************************************************
  10. */
  11. var height = "61";
  12.  
  13.  
  14. switch (height)
  15. {
  16. case 59:
  17. document.write("Height is less than 5 feet");
  18. break;
  19. case 60:
  20. document.write("Height is equal to 5 feet");
  21. break;
  22. case 61:
  23. document.write("height is more than 5 feet");
  24. break;
  25. default:
  26. document.write("height is out of 59 inch to 61 inches");
  27. }
  28.  
  29. //-->
  30. </script>
  31. </body>
  32. </html>


- If the string defined

var height = "61"; would have matched with the

case 61 :

It would have produced an output "height is more than 5 feet". Instead it gives the output "height is out of 59 inch to 61 inches". The reason is simple - the types do not match. This happens because switch uses ==== in place of == when comparing the values.

You can try this example online here.

Javascript switch different types

A way to fix this is either change

var height = "61";

to

var height = "1;

or change

case 61 :

to

case 61 :