Home » Javascript » Switch Statement

Switch Statement

The switch statement of JavaScript

The switch statement is basically an enhanced version of the “if-else” statement that is more convenient to use when you have code that needs to choose a path from many to follow. Starting with JavaScript 1.2, we can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if…else if statements. The switch statement is used to perform different action based on different conditions.

Syntax for Switch Statement

The basic syntax for the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The switch statement always begin with the keyword “switch”, plus a required parameter that contains the expression (or variable) you wish to evaluate. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

switch(e)
{
case 1:
  execute code block 1
  break;
case 2:
  execute code block 2
  break;
default:
  code to be executed if e is different from case 1 and 2
}

Parameters in Switch Statement

expression

An expression matched against each label.

label

Identifier used to match against expression.

statements

Statements that are executed if expression matches the associated label.

statement default

Statements that are executed if expression does not match any label.

First we have a single expression e (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.
The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

Example

Let’s see an exaple using days of a week

var e;
var day=new Date().getDay();
switch (day)
{
case 0:
  e="It's Sunday";
  break;
case 1:
  e="It's Monday";
  break;
case 2:
  e="It's Tuesday";
  break;
case 3:
  e="It's Wednesday";
  break;
case 4:
  e="It's Thursday";
  break;
case 5:
  e="It's Friday";
  break;
case 6:
  e="It's Saturday";
  break;
} 

This will produce the result, that is current day.

See more about Javascript Switch statement

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*