- read

Goodbye if-else, Hello Pattern Matching in JavaScript (PROPOSAL)

Code Everywhere 64

Goodbye if-else, Hello Pattern Matching in JavaScript (PROPOSAL)

Code Everywhere
JavaScript in Plain English
3 min readOct 1

--

This article is a proposal suggesting the use of “pattern matching” in JavaScript as an alternative to traditional “if-else” and “switch-case” structures.

In the ever-evolving realm of software development, adaptability is not just a skill but a necessity. Among the vast sea of languages, JavaScript has time and again proven its resilience, adapting to the ever-changing demands of the industry. As whispers of “pattern matching” grow louder, it’s clear that the traditional bastions of if-else and switch-case might soon be relics of the past. The winds of change are blowing, hinting at a more streamlined and efficient approach to conditional logic. Dive with us into this transformative journey as we explore the exciting prospects of pattern matching in JavaScript's future landscape.

1. Taking a Nostalgic Walk: The Era of if-else and switch-case

Seasoned developers remember starting their JavaScript journey with traditional conditional constructs like if-else and switch-case. Such structures are akin to the ABCs of the language.

Consider a rudimentary representation of handling action types in a backend system:

function handleAction(actionName) {
if (actionName === 'FETCH_DATA') {
return fetchData();
} else if (actionName === 'UPDATE_RECORD') {
return updateRecord();
} else if (actionName === 'DELETE_RECORD') {
return deleteRecord();
} else {
return 'Invalid Action';
}
}
function handleAction(actionName) {
switch (actionName) {
case 'FETCH_DATA':
return fetchData();
case 'UPDATE_RECORD':
return updateRecord();
case 'DELETE_RECORD':
return deleteRecord();
default:
return 'Invalid Action';
}
}

Though clear, as our system expands and incorporates more actionNames, this structure starts showing its strain.

2. Unearthing the Magic: The Brilliance of when

The inception of the when keyword heralds a transformative era. Using when, our earlier example morphs into:

function handleAction(actionName) {
return actionName when {
'FETCH_DATA' -> fetchData(),
'UPDATE_RECORD' -> updateRecord(),
'DELETE_RECORD' ->…