DEV Community

Cover image for Enhancing JavaScript Code: Using Objects Instead of Switch Statements
Nassbin
Nassbin

Posted on

Enhancing JavaScript Code: Using Objects Instead of Switch Statements

Introduction

This is a short and somewhat unusual topic to write about, but I haven’t encountered it much on the web while working, so here is my contribution. I would love to hear people’s opinions on this method since I use it regularly. I don’t like writing multiple cases inside a switch statement, so I found using an object to be a cleaner alternative. It may not be faster, but the code looks cleaner to me.

Demonstration

I want to handle orders with different payment statuses and apply different treatments depending on whether they are paid or not.

Let's begin with this:

const orders = [{
  "id": 1,
  "product": "shoes",
  "paymentStatus": "Paid"
},{
  "id": 2,
  "product": "pants",
  "paymentStatus": "Pending"
},{
  "id": 3,
  "product": "tie",
  "paymentStatus": "UnPaid"
}];


const handlePaymentStatus =(order) =>{
  return order.paymentStatus
}

for (const order of orders) {
 handlePaymentStatus(order)
}
Enter fullscreen mode Exit fullscreen mode

We want to apply a specific treatment based on the order.paymentStatus. A simple solution would be to use a switch statement like this:

let orders = [{
  "id": 1,
  "product": "shoes",
  "paymentStatus": "Paid"
},{
  "id": 2,
  "product": "pants",
  "paymentStatus": "Pending"
},{
  "id": 3,
  "product": "tie",
  "paymentStatus": "Unpaid"
}];


const handlePaymentStatus =(order) =>{
switch (order.paymentStatus) {
  case 'Paid':
    console.log("it's all good");
    break;
  case 'Unpaid':
    console.log("need to be paid");
    break;
  default:
    console.log(`We'll wait`);
}
}

for (const order of orders) {
 handlePaymentStatus(order)
}
Enter fullscreen mode Exit fullscreen mode

It's a simple case since we have two options and a default, but imagine it with multiple payment methods. We’ll keep it like this for the purpose of clarity:

let orders = [{
  "id": 1,
  "product": "shoes",
  "paymentStatus": "Paid"
},{
  "id": 3,
  "product": "tie",
  "paymentStatus": "Unpaid"
},{
  "id": 2,
  "product": "pants",
  "paymentStatus": "Pending"
},];

const paymentStatusHandlers = {
  'Paid': () =>  console.log("it's all good"),
  'Unpaid': () => console.log("needs to be paid"),
}

for (const order of orders) {
 paymentStatusHandlers[order.paymentStatus] 
    ? paymentStatusHandlers[order.paymentStatus]()
    : console.log("We'll wait")
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using an object instead of a switch statement can make your code more readable and maintainable, especially when dealing with multiple cases. It’s a matter of personal preference, but it’s worth considering as an alternative approach.

Feel free to let me know if there are any other specific changes or additions you'd like to make!

Top comments (1)

Collapse
 
alexmustiere profile image
Alex Mustiere

Your code reminds me of the "Strategy" pattern. You could have written this:

const orders = [
  {
    id: 1,
    product: 'shoes',
    paymentStatus: 'Paid',
  },
  {
    id: 3,
    product: 'tie',
    paymentStatus: 'Unpaid',
  },
  {
    id: 2,
    product: 'pants',
    paymentStatus: 'Pending',
  },
];

const paymentStrategy = {
  of: (status) => paymentStrategy.statuses[status] ?? paymentStrategy.statuses.default,
  statuses: {
    Paid: {
      handler: () => {
        console.log(`it's all good`);
      },
    },
    Unpaid: {
      handler: () => {
        console.log(`needs to be paid`);
      },
    },
    default: {
      handler: () => {
        console.log(`We'll wait`);
      },
    },
  },
};

for (const order of orders) {
  paymentStrategy.of(order.paymentStatus).handler();
}
Enter fullscreen mode Exit fullscreen mode

It's quite similar but:

  • if you have a new status you juste have to change the code in the strategy
  • if you need to define other action(s) for each status, you just have to add method(s) attached to the different statuses