Lecture 5 – Switch Statement

If..else if statements help you evaluate multiple conditions at the same time. However, this is not the best solution, especially if a single variable controls all the conditions and statements. If you find yourself in this situation, the ideal course of action is to use a switch statement instead of repeating if..else if statement.

A switch statement normally has a value of only one variable to evaluate. Based on this variable, it has to execute one of multiple statements. JavaScript tries to find the exact match by checking each statement against the value of the variable. It only stops when it finds that match. It uses a default condition when exact match is not found.

The following is the syntax of the switch statement.

switch (expression) {
   case condition 1: statement(s)
   break;
   
   case condition 2: statement(s)
   break;
   ...
   
   case condition n: statement(s)
   break;
   
   default: statement(s)
}

We use Break statement to end every single case in the switch statement otherwise the interpreter will execute each case in the descending order.

Now we go through an example of switch statement.

<!DOCTYPE html>
<html lang="en">
<head>
    
</head>
<body>
                
                    
                       var position = 'First';
                      
                       switch (position) {
               case 'Second': document.write("Good Work
"); break; case 'Third': document.write("Excellent Work
"); break; case 'First': document.write("Exceptional Work: Good Job
"); break; case 'Fourth': document.write("Not so good
"); break; case 'Fifth': document.write("Poor Work
"); break; default: document.write("Unknown position
") } </body> </body> </html>

The interpreter in the above code will evaluate each case against the value of the variable “position.” It will execute the third case because it is the exact same match, making switch statements a much better solution compared to the if and if..else statements.

In the next lecture, we will shed some light on JavaScript Loops and study them in detail.