Master JavaScript Programming From Scratch

Clear, interactive, and structured JavaScript lessons designed for absolute beginners.

Switch

Learn how to select one block of code from multiple possible options using the JavaScript switch statement.

What is switch?

The switch statement evaluates an expression and compares its value with different case values.

When a matching case is found, its code executes. The break statement normally stops execution from continuing into the next case.

Decision and code concept

A switch statement helps a program choose from multiple options.

Main Parts of switch

S
switch

Contains the expression whose value needs to be checked.

C
case

Defines a value that can match the switch expression.

D
default

Runs when none of the case values match.

Basic Syntax

switch (expression) {
    case value1:
        // code
        break;

    case value2:
        // code
        break;

    default:
        // code
}

How switch Works

Expression → Match Case → Execute Code
Expression Example: day = 2
→
Compare Cases 1, 2, 3, 4...
→
Matching Case case 2
→
Execute Run matching code
case 1 Monday
case 2 Tuesday
case 3 Wednesday
default Other Day

Example 1: Days of the Week

In this example, the switch statement checks a number and prints the corresponding day.

const day = 2;

switch (day) {
    case 1:
        console.log("Monday");
        break;

    case 2:
        console.log("Tuesday");
        break;

    case 3:
        console.log("Wednesday");
        break;

    default:
        console.log("Invalid Day");
}

Output

Tuesday

Example 2: Course Selection

A switch statement can also be used to select an action based on a course code.

const courseCode = "JS";

switch (courseCode) {
    case "JAVA":
        console.log("Java Full Stack");
        break;

    case "DOTNET":
        console.log(".NET Full Stack");
        break;

    case "JS":
        console.log("JavaScript Full Stack");
        break;

    default:
        console.log("Course Not Found");
}

Output

JavaScript Full Stack

Important Note

Why use break?

The break statement stops the switch after the matching case has executed.

Without break, JavaScript can continue executing statements in subsequent cases.

Summary

The switch statement is useful when one expression needs to be compared with multiple possible values. A case defines a possible match, break stops further case execution, and default handles the situation when no case matches.