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.
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) }
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) }
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") }
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!
The above is the detailed content of Enhancing JavaScript Code: Using Objects Instead of Switch Statements. For more information, please follow other related articles on the PHP Chinese website!