Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

JavaScript Switch


The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement that we have learned in previous page. But it is convenient than if..else..if because it can be used with numbers, characters etc.

The signature of JavaScript switch statement is given below.

  1. switch(expression){
  2. case value1:
  3.  code to be executed;
  4.  break;
  5. case value2:
  6.  code to be executed;
  7.  break;
  8. ……
  9. default:
  10.  code to be executed if above values are not matched;
  11. }

Let’s see the simple example of switch statement in javascript.

  1. <script>
  2. var grade=‘B’;
  3. var result;
  4. switch(grade){
  5. case ‘A’:
  6. result=“A Grade”;
  7. break;
  8. case ‘B’:
  9. result=“B Grade”;
  10. break;
  11. case ‘C’:
  12. result=“C Grade”;
  13. break;
  14. default:
  15. result=“No Grade”;
  16. }
  17. document.write(result);
  18. </script>

Test it Now

Output of the above example

B Grade

The switch statement is fall-through i.e. all the cases will be evaluated if you don’t use break statement.

Let’s understand the behaviour of switch statement in JavaScript.

  1. <script>
  2. var grade=‘B’;
  3. var result;
  4. switch(grade){
  5. case ‘A’:
  6. result+=” A Grade”;
  7. case ‘B’:
  8. result+=” B Grade”;
  9. case ‘C’:
  10. result+=” C Grade”;
  11. default:
  12. result+=” No Grade”;
  13. }
  14. document.write(result);
  15. </script>

Test it Now

Output of the above example

B Grade B Grade C Grade No Grade

Comments

comments