SWITCH STATEMENT EXAMPLE IN JAVASCRIPT | BASICS

Share the post

Hello all, In part-1 we have discussed array & if, if-else statements. Whereas in part-2, for loop, while & do-while loop. Now, in this part-3 we will discuss the switch statements. What is the switch statement?  What is the syntax of the switch statement? switch statement example in JavaScript? All questions will be answered in this topic. So, let’s see step by step.

 

What is the switch statement ? 

When we have to perform a multiple actions based on condition then will use switch-case statement.
 

Syntax : 

switch (value)
 
{
 
    case a :  
                // CODE
                break;
    case b :  
                // CODE
                break;
    case c :  
                // CODE
                break;
    default : 
                // CODE
 
}

 

SWITCH STATEMENT EXAMPLE IN JAVASCRIPT :

 
       
switch (x = 1)
 
{
 
    case 1 :  
                console.log(“This is case 1.”);
                break;
    case 2 :  
                console.log(“This is case 2.”);
                break;
    case 3:  
                console.log(“This is case 3.”);
                break;
    default : 
               console.log(“This is default case.”);
}

 
 

Output : 

 
output
 
 
 

In above example we have seen that we try to match the value of switch statement with the different cases. In our case we are matching value 1 of switch statement with case 1 & console the log “This is case 1”. 

 
    

Leave a Comment