How to use javascript switch statements?

In this article, lets discuss the usage of the javascript switch statements. Javascript swtich statement is a part of Conditional statements which is used to execute different statements based on different conditions. This is also a better alternative for nested IF/Else statement.

Javascript switch statement evaluates an expression and the value of the evaluation is compared with the values in the each case structure. If there is a match then the associated Case block will be executed. The switch statement is often used together with break and default keywords. However, these keywords are optional.

Optional blocks of Switch

Break keyword breaks out the switch block. It means, it stops the execution of the consequent case blocks.

Default keyword is used to specify the set of code which needs to be executed when there is no case match. There can be only one default block in a switch statement. Although this default block is optional, it is recommended to use it handle the unexpected cases.

Syntax

switch(expression) {

  case a:

   /* code block to be executed when the expression is evaluated to 'a' */

    break;

  case b:

    /* code block to be executed when the expression is evaluated to 'b' */

    break;

  default:

    /* code block to be executed when the expression is not evaluated to 'a' or 'b' */

}

Example

var day;

switch (new Date().getDay()) {

  case 0:

    day = "Sunday";

    break;

  case 1:

    day = "Monday";

    break;

  case 2:

    day = "Tuesday";

    break;

  case 3:

    day = "Wednesday";

    break;

  case 4:

    day = "Thursday";

    break;

  case 5:

    day = "Friday";

    break;

  case 6:

    day = "Saturday";

    break;

  default:

    day = "Unknown Day";

}

This is the syntax and usage guide of the javascript switch statement.

See also:

Javascipt try catch statements

Thanks for reading this tutorial. If you have any questions or improvements with respect to this tutorial, Please feel free the comment below or send me an email at [email protected]

Summary
how to use javascript switch statement?
Article Name
how to use javascript switch statement?
Description
This article explains how to use javascript switch statement which is used to perform different actions based on the different conditions with examples.
Author
Publisher Name
askvikram.com
Publisher Logo

Leave a Comment