Eliaz Bobadilla
UltiRequiem's Blog

UltiRequiem's Blog

Switch Statements to Object Literals

Switch Statements to Object Literals

More natural control of flow in JavaScript ✨

Eliaz Bobadilla's photo
Eliaz Bobadilla
Β·Jul 25, 2022Β·

4 min read

Table of contents

  • Hey everyone! πŸ‘‹
  • What is the Switch Statement?
  • Problems with switch
  • Object Literals
  • Object literal fall-through
  • Summing Up

Hey everyone! πŸ‘‹

Hello There GIF

This is UltiRequiem here. I'm a 15-year-old, Peruvian πŸ‡΅πŸ‡ͺ, full-stack and system developer, with the intention to become a successful Software Engineer.

Today I will explain the problems with the switch statement in JavaScript and my personal solution, object literals ✨

What is the Switch Statement?

The switch statement is used to perform different actions based on different conditions.

"The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered. The default clause of a switch statement will be jumped to if no case matches the expression's value."

-- > MDN Web Docs

Let's look at this example πŸ‘‡

const expr = "Papayas";

switch (expr) {
  case "Oranges":
    console.log("Oranges are $0.59 a pound.");
    break;
  case "Mangoes":
  case "Papayas":
    console.log("Mangoes and papayas are $2.79 a pound.");
    break;
  default:
    console.log(`Sorry, we are out of ${expr}.`);
}

// expected output: "Mangoes and papayas are $2.79 a pound."

It’s similar to if and else statements, but it should evaluate a single value - inside the switch we use a case to evaluate against each value.

Something is probably wrong when you start seeing a lot of else and if statements, and in most cases you should use something like switch because it is better suited for the intended use.

Here’s some else and if abuse πŸ‘‡

function permissionLeve(user) {
  if (user.type === "administrator") {
    return 3;
  } else if (user.type === "helper") {
    return 2;
  } else if (user.type === "user") {
    return 1;
  } else {
    return 0;
  }
}

Problems with switch

  • Non-standard look

The rest of JavaScript uses curly braces yet switch does not.

  • break

We’re forced to manually add break statements within each case, which can lead to difficult debugging and nested errors further down the case should we forget.

  • Big O notation: O(n)

Although this should not be a problem unless you work with huge inputs, it is important to mention it.

Object Literals

We can implement the previous function using an Object literal as follows πŸ‘‡

function permissionLeve(user) {
  const permissions = { administrator: 3, helper: 2, user: 1 };

  return permissions[user.type] ?? 0;
}

Nullish coalescing operator (??)

We saved a few lines of code and overall is more readable.

In cases where more complex things need to be done, we can also store functions inside an object literal πŸ‘‡

function makeFood(user) {
  const foodMakers = {
    administrator() {
      makePizza();
    },
    helper() {
      makeSandwich();
    },
    user() {
      makeApple();
    },
  };

  return foodMakers[user.type]();
}

More maintainable and readable.

We also don’t have to worry about break statements and cases falling through - it’s just a plain Object.

Object literal fall-through

With switch cases, we can let them fall through (which means more than one case can apply to a specific piece of code).

"You can use the break statement within a switch statement's body to break out early, often when all statements between two case clauses have been executed. Execution will continue at the first statement following switch.

If break is omitted, execution will proceed to the next case clause, even to the default clause, regardless of whether the value of that clause matches.

-- > MDN Web Docs

Example πŸ‘‡

const type = 'coke';

let snack;

switch(type) {
case 'coke':
case 'pepsi':
  snack = 'Drink';
  break;
case 'cookies':
case 'crisps':
  snack = 'Food';
  break;
default:
  drink = 'Unknown type!';
}

console.log(snack); // 'Drink'

Doing this for Object Literals is simpler and more declarative - as well as being less prone to error. Our code suddenly becomes much more structured, readable, and reusable πŸš€

function snack(type) {
  let snack;

  function isDrink() {
    snack = "Drink";
  }

  function isFood() {
    snack = "Food";
  }

  const snacks = {
    coke: isDrink,
    pepsi: isDrink,
    cookies: isFood,
    crisps: isFood,
  };

  return snacks[type]();
}

Summing Up

Object literals are a more natural control of flow in JavaScript, switch is a bit clunky and prone to difficult debugging errors.

Objects are more extensible, and maintainable, and we can test them a lot better.

I have been preferring to use Object literals over a switch for some time, did this article convince you to do the same? 🧐

Cheers πŸ›«

Β 
Share this