How to useTraditional Switch Statement in Javascript

The switch statement in JavaScript has been used for the basic conditional branching. While not as advanced as dedicated pattern matching it can be used creatively to achieve similar results.

Syntax:

switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

Example: In this example, GFG function with parameter ‘fruits’ uses switch for selection checks. Prints respective messages. Tested with different fruit values.

Javascript




function GFG(fruits) {
    switch (fruits) {
        case "apple":
        case "banana":
            console.log(`You selected ${fruits}`);
            break;
        case "orange":
            console.log(`You selected an ${fruits}`);
            break;
        default:
            console.log("Unknown fruit");
    }
}
GFG("Mango");
GFG("orange");
GFG("Apple");


Output

Unknown fruit
You selected an orange
Unknown fruit

JavaScript Program for Pattern Matching for Switch

In this article, we will learn about Pattern Matching for Switch using Javascript, Pattern matching is a programming language feature that allows you to match values against patterns and execute corresponding blocks of code. While JavaScript has traditionally used the switch statement for conditional branching modern proposals are introducing a more powerful form of pattern matching for the switch.

We will cover two different approaches to provide hands-on implementation examples for each approach.

Table of Content

  • Using Traditional Switch Statement:
  • Using Object Literal Mapping

We will explore all the above methods along with their basic implementation with the help of examples.

Similar Reads

Approach 1: Using Traditional Switch Statement

...

Approach 2: Using Object Literal Mapping

The switch statement in JavaScript has been used for the basic conditional branching. While not as advanced as dedicated pattern matching it can be used creatively to achieve similar results....