Switch statement have been a staple of JavaScript for conditionals. But what if there’s a more readable and maintainable way? Enter object literals, JavaScript’s versatile data structures, offering a compelling alternative to switch statements in many scenarios.
Table of contents
Open Table of contents
Why Consider Objects?
While switch statements work well, they can become cumbersome with numerous cases. Here’s where objects shine:
- Readability: Object literals map conditions (keys) to actions (values), making code intent clearer.
- Maintainability: Adding new cases involves simply adding a key-value pair, keeping logic organized.
- Flexibility: Objects can hold functions as values, allowing for more complex logic within each case.
- Default Handling: The optional default key is great for handling any unmatched conditions.
Making the Switch 🥸
Let’s see how an object can replace a switch statement. Imagine a function that greets users based on their language preference:
function greet(language) {
switch (language) {
case "en":
return "Hello!";
case "es":
return "¡Hola!";
default:
return "Hi!";
}
}
Here’s the equivalent using an object:
const greetings = {
en: () => "Hello!",
es: () => "¡Hola!",
default: () => "Hi!",
};
function greet(language) {
return greetings[language] ? greetings[language]() : greetings.default();
}
The object greetings
stores greetings for specific languages. The function retrieves the appropriate greeting using bracket notation and calls it as a function if it exists. Otherwise, the default greeting is returned.
When to Use This Approach
While objects offer advantages, consider these points:
- Performance: Switch statements might have a slight performance edge for simple lookups.
- Complexity: For intricate logic within cases, functions within objects might be preferable.
Source(s)
The inspiration to write this post comes from this TomDoesTech video I came across way back. I think Tom makes really great videos and his channel is worth giving a look 🙏.