Skip to content

Objects: A Clean Alternative to Switch Statements in JavaScript

Published:

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:

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:

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 🙏.