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
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using Traditional Switch Statement
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.
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" );
|
Unknown fruit You selected an orange Unknown fruit
Approach 2: Using Object Literal Mapping
In this approach, we Create an object mapping with patterns as keys and values. Match input to object keys and return corresponding value or default response.
Syntax:
function Fruit(fruits) {
const fruitActions
{
default: () => console.log(`Unknown fruits`)
};
(fruitActions[fruits] || fruitActions.default)();
};
Example: In this example, The Fruit function takes “fruits.” fruitActions obj holds actions. It runs matching actions, else console Unknown.
function Fruit(fruits) {
const fruitActions = {
apple: () => console.log(`You selected Mango`),
banana: () => console.log(`You selected Apple`),
orange: () => console.log(`You selected an orange`),
default : () => console.log(`Unknown fruits`)
};
(fruitActions[fruits] || fruitActions. default )();
} Fruit( "Mango" );
Fruit( "orange" );
Fruit( "grape" );
|
Unknown fruits You selected an orange Unknown fruits