HOLLA TECH - LEARN

Switch
 

In cases when you need to test for multiple conditions, writing if else statements for each condition might not be the best solution.
The switch statement is used to perform different actions based on different conditions.

Syntax: 

switch (expression) {
case n1:
     statements
     break;
case n2:
     statements
     break;
  default:
     statements

 

The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed.

NOTE!
You can achieve the same result with multiple if…else statements, but the switch statement is more effective in such situations.

The switch Statement
 

Consider the following example.

var day = 2;
switch (day) {
  case 1:
    document.write(“Monday”);
    break;
  case 2:
    document.write(“Tuesday”);
    break;
  case 3:
    document.write(“Wednesday”);
    break;
  default:
    document.write(“Another day”);
}

// Outputs “Tuesday”

]/su_quote] 

NOTE!
You can have as many case statements as needed.

The break Keyword
 

When JavaScript code reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.

NOTE!
Usually, a break should be put in each case statement.

The default Keyword
 

The default keyword specifies the code to run if there is no case match.

var color ="yellow";
switch(color) {
   case "blue":
     document.write("This is blue.");
     break;
   case "red":
     document.write("This is red.");
     break;
   case "green":
     document.write("This is green.");
     break;
   case "orange":
      document.write("This is orange.");
      break;
   default:
      document.write("Color not found.");
}

//Outputs "Color not found." 

 

NOTE!
The default block can be omitted, if there is no need to handle the case when no match is found.

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE JAVASCRIPT MAIN COURSE PAGE. 

JAVASCRIPT MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT