The Wayback Machine - https://web.archive.org/web/20241118082451/https://www.geeksforgeeks.org/javascript-program-for-pattern-matching-for-switch/
Open In App

JavaScript Program for Pattern Matching for Switch

Last Updated : 17 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

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.

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

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.

JavaScript
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");

Output
Unknown fruits
You selected an orange
Unknown fruits




Similar Reads

Wildcard Pattern Matching in JavaScript
In this article, we will see Pattern matching with wildcards which is an encountered problem, in the field of computer science and string manipulation. The objective is to determine whether a given wildcard pattern matches a string or not. In this article, we will discuss the step-by-step algorithm for wildcard pattern matching providing code examp
4 min read
Less.js Mixins Pattern-matching
Less.js is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is preferable since CSS is a dynamic style sheet language. LESS can be utilized by many different browsers because it is versatile. Web browsers can only use CSS that has been developed and processed using a co
3 min read
Pattern Matching In TypeScript
Pattern matching refers to the ability to check a value against a pattern and execute code based on the matching result, although TypeScript lacks native pattern matching we can implement similar functionality using control flow constructs like switch, type guards, and destructuring. This allows TypeScript to perform operations based on types, valu
5 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest common prefix in both of them? It is “geeks”.Now let us introduce
3 min read
How to return all matching strings against a regular expression in JavaScript ?
In this article, we will learn how to identify if a string matches with a regular expression and subsequently return all the matching strings in JavaScript. We can use the JavaScript string.search() method to search for a match between a regular expression in a given string. Syntax: let index = string.search( expression )Parameters: This method acc
3 min read
Password Matching using JavaScript
In an online application form or social media signup page, it's common to have two input fields: one for the password and another for confirming the password. The goal is to check whether the entered passwords match. To achieve this, the first password is stored in a variable password1, and the confirmation password is stored in password2. We then
2 min read
How to optimize the switch statement in JavaScript ?
The switch statement is necessary for certain programming tasks and the functionality of the switch statement is the same among all programming languages. Basically switch statements switch the cases as per the desired condition given to the switch. A switch statement can be used when multiple numbers of consecutive if/else statement is in use. But
2 min read
How to add bootstrap toggle-switch using JavaScript ?
Bootstrap toggle-switch is a simple component used for activating one of the two given options. Commonly used as an on/off button. The CSS framework is a library that allows for easier, more standards-compliant web design using the Cascading Style Sheets language. Bootstrap 4 is one such widely used CSS framework used by web developers for building
2 min read
How to Redeclare a Variable Inside a Switch Block in JavaScript ?
Generally, in JavaScript, if you try to declare a variable with the same name inside a switch block will throw a syntaxError for declaring the variable again in the same block using the let keyword. We can overcome this problem by enclosing the code for every case statement inside a block using the curly brackets({}) and then redeclare the variable
1 min read
How to write a switch statement in JavaScript?
In JavaScript, a switch statement is a control flow statement that evaluates an expression and executes code based on matching cases. It provides a more concise and readable way to handle multiple possible conditions compared to nested if...else statements. Syntax:switch (expression) { case value1: // code block to be executed if expression matches
2 min read
JavaScript switch Statement
The JavaScript switch statement evaluates an expression and executes a block of code based on matching cases. It provides an alternative to long if-else chains, improving readability and maintainability, especially when handling multiple conditional branches. Table of Content Switch Statement SyntaxHow Switch Statement WorksFlowchart of Switch Stat
5 min read
How to switch the language of the page using JavaScript ?
Switching the language of a webpage using JavaScript involves dynamically changing the text content based on the user's language selection. This can be done by loading language-specific text from a predefined dataset, translating page elements, or reloading content from a localized source using JavaScript. ApproachHTML Structure: The page includes
3 min read
How to Switch Between Multiple CSS Stylesheets using JavaScript?
To switch between multiple CSS stylesheets using JavaScript, the href attribute of the <link> element can be changed dynamically in the HTML document that links to the stylesheets. <link id="theme" rel="stylesheet" type="text/css" href="light.css" /> The "href" attribute specifies the file location of the CSS file. By altering this tag,
2 min read
How to Use RegExp in Switch Case Statements in JavaScript?
Using regular expressions (RegExp) in switch statements in JavaScript is a bit unconventional because switch statements typically use strict equality comparison (===). However, you can still achieve similar functionality by combining switch with case labels and if or else if statements for regular expression matching. Here's how you can use RegExp
2 min read
Compare usage of Module Pattern vs Constructor/Prototype pattern ?
The Module pattern and the Constructor/Prototype pattern are two popular design patterns in JavaScript that can be used to create objects. Both patterns have their own pros and cons and are suitable for different scenarios. Here's a comparison of the two patterns: Module pattern: The Module pattern is a design pattern used to create objects that ha
6 min read
Less.js Extend Exact Matching with Extend
LESS is a simple CSS pre-processor that makes it possible to create manageable, customizable, and reusable style sheets for websites. LESS is a dynamic style sheet language that increases the working power of CSS. LESS is cross-browser compatible. CSS pre-processor is a scripting language that improves CSS and gets compiled into regular CSS syntax
3 min read
How to find Objects Containing Matching Elements from Arrays in Another Object ?
The task is to find objects that contain matching elements from arrays in another object. An object containing an array of values and a separate object. The objective is to determine whether the values present in the array are also present as keys in the separate object. These are the following methods: Table of Content Using forEach loopUsing filt
4 min read
How to get Matching Data from a Prompt on an Existing Object ?
In JavaScript, getting matching data from an object can be done using various approaches like using traditional looping or by using the Object properties. JavaScript provided various approaches for matching data from a prompt on an existing object which are as follows: Table of Content Using for...in LoopUsing Object.hasOwnProperty Using for...in L
3 min read
Explain Route matching priority in VueJS ?
Route MatchingRoute Matching is the concept in which the Vue Router specifies which component is to be rendered according to the URL entered by the end user. If the user navigates to any specific URL, Vue Router checks for the defined routes and finds the match for that URL. It later compares the entered URL with the path patterns specified in the
7 min read
How to Create TypeScript Generic Function with Safe Type Matching ?
In TypeScript, generic functions offer a powerful tool for creating flexible and reusable code that can work with various data types. However, ensuring type safety is crucial to prevent runtime errors and maintain code reliability. These are the following approaches:Table of Content Using Type constraintsUsing Type inferenceUsing Type guardsConclus
4 min read
How to Define Generic Type for Matching Object Property Types in TypeScript ?
In Typescript, efficiently managing object property types is essential for type safety and code maintainability. Several techniques can be used to define generic types that match the properties of the objects as listed and explained below. Table of Content Using Record Utility TypeUsing Mappped TypesUsing Partial utility typeUsing intersection Oper
4 min read
JavaScript Program for Hollow Pyramid Star Pattern
In this article, we will demonstrate how to create Hollow Pyramid Star Patterns in JavaScript. Possible Hollow Pyramid Star Patterns areUpper pyramidInverted pyramidLeft inverted pyramidRight inverted pyramidApproachThere will be two different approaches based on alignments i.e. horizontal and vertical: Horizontally Inverted PyramidVertically Inver
3 min read
JavaScript Program to Print Pyramid Star Pattern
In this article, we will demonstrate how to create pyramid star patterns in JavaScript. The Possible Pyramid Star Patterns are:Upper pyramidInverted pyramidLeft inverted pyramidRight inverted pyramidApproachThere will be two different approaches based on alignments i.e. horizontal and vertical. Horizontally Inverted PyramidThis type includes the up
3 min read
JavaScript Program to Print Diamond Shape Star Pattern
This article will demonstrate how to create the diamond start pattern in JavaScript. Possible Diamond Start Patterns:Solid Diamond Start PatternHollow Diamond Star PatternInverted Hollow Diamond PatternApproach to Create Diamond Star Pattern:The approach to creating a diamond star pattern will use 2 JavaScript Nested For loops to print the upper an
3 min read
JavaScript Program to Print Matrix in Diagonal Pattern
We have given the n*n size matrix and we need to print the elements of this matrix in the diagonal pattern using JavaScript language. Below are the examples for a better understanding of the problem statement. Examples:Input: mat[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output:1 2 4 7 5 3 6 8 9Explanation:Start from 1 Then from upward to downward d
4 min read
JavaScript Program to Print Pyramid Pattern by using Numbers
A pyramid pattern using numbers is a sequence of numbers arranged in a triangular shape, with each row displaying incrementing or decrementing numbers, creating a visually structured pattern. Example: 1 1 2 3 1 2 3 4 5 1 2 3 4 5 6 71 2 3 4 5 6 7 8 9ApproachWe initialize a variable n with the value 5. This variable determines the number of rows in t
5 min read
JavaScript Program to Print Number Pattern
The idea of pattern-based programs is to understand the concept of nesting for loops and how and where to place the alphabet/numbers/stars to make the desired pattern. These are the following approaches to printing different types of number patterns:Table of Content Using nested loops Using array manipulation and join() methodApproach 1: Using nest
2 min read
JavaScript Program to Print Reverse Floyd Pattern Triangle Pyramid
Printing a reverse Floyd pattern triangle pyramid involves outputting a series of numbers in descending order, forming a triangular shape with each row containing one less number than the previous row. The numbers are arranged in such a way that they form a right-angled triangle, reminiscent of Floyd's triangle, but in reverse order. Example: Input
2 min read
JavaScript Program to Print the Pattern G
This program aims to print the pattern 'G' using asterisks (*) in the console output. The pattern 'G' consists of several horizontal and vertical lines arranged to form the uppercase letter 'G'. It requires careful positioning of asterisks to represent the shape accurately. Below are the methods to print the G pattern: Table of Content Using 2D mat
3 min read
JavaScript Program to Print Double Sided Stair-Case Pattern
This JavaScript program is designed to print a double-sided staircase pattern. A double-sided staircase consists of steps where each step has numbers incrementing from 1 to the current row number on the left side, and then decrementing from the current row number - 1 down to 1 on the right side. The staircase is printed in a format where each row i
3 min read
three90RightbarBannerImg