You are currently viewing JavaScript Switch Statement

JavaScript Switch Statement

JavaScript Switch Statement

You should know Conditional Statement in JavaScript. Because it is like an else if statement. But it is more convenient to use. 

The Switch Statement evaluates an expression and executes the corresponding case that matches the expression result. And this is continued till you have not reached a break statement or a default clause.

The default is executed if there is no matching case to the expression result.

Syntax of JavaScript Switch Statement

switch(expression) {
case value1:
// body of case 1
break;

case value2:
// body of case 2
break;

case valueN:
// body of case N
break;

default:
// default clause execute only if no case matches.
// body of default
}

Break is used to break the switch statement. But it is optional. Also, the default clause is optional.

Flowchart of Switch Statement

Flowchart

Example of Switch Statement

To print Day name

When Day=1 , it will match to case 1 and print Monday and the break statement will terminate the switch case. Similarly, Day =2 to 7 corresponding days will gets printed.

// To print Day name by entering Day number
let Day = 4;

switch(Day){
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    case 3:
        console.log("Wednesday");
        break;
    case 4:
        console.log("Thursday");
        break;
    case 5:
        console.log("Friday");
        break;
    case 6:
        console.log("Saturday");
        break;
    case 7:
        console.log("Sunday");    
}

Article written By: : Ankita Kataria.

Check about Synchronous and Asynchronous JavaScript.

#JavaScript Switch Statement

Thank you !!

Leave a Reply