Object literals an alternative for if/else statements.

Kailas Pk
2 min readDec 14, 2022

--

As a software dev we can’t avoid if/else statements and else/if ladders in our day to day coding life. Even though if statements are crucial in certain situations, for some exceptions use of if statements can be avoid as it effects the performance. Considering the performance and the code optimization object literals are the perfect solution.

Use of else/if ladder

const orderStatus = 'OLD';
if (orderStatus == 'NEW') {
console.log('This is a new order');
} else if (orderStatus == 'OLD') {
console.log('This was an old order');
} else if (orderStatus == 'CANCELED'){
console.log('This was a canceled order');
}
//This was an old order

Here we create a variable: orderStatus which is a string and we check orderStatus with conditions using else/if ladder, we will get the output as ‘this was an old order’. Use of else/if condition will show a major effect in the performance.

Use of object literals

What Object Literals are, and why do we use them? An object literal is a list of name-value pairs separated by commas inside of curly braces. Those values can be properties and functions. More importantly we can assign object literals to other variables as it only creates the copy of the original values.

const orderStatus = async (type) => {
let Orders = {
NEW: async () => {
let one = 'This is a new order'
return one;
},
OLD: async () => {
let two = 'This was an old order'
return two;
},
CANCELED: async () => {
let three = 'This was a canceled order'
return three;
}
};
return await Orders[type]();
}

await orderStatus('OLD');
//This was an old order

Here we have the same scenario as of the above if condition, but the difference is we used object literals for this. we created a function for which it returns the response. Both the code will return the same response but the performance matters.

Object literals name-value pairs


let name = 'user name';
let veriable = {
[name]: 'Dev',
'work hours': 90
};

console.log(veriable['user name']); // Dev
console.log(veriable['work hours']); // 90

In this example you can see that while calling the veriable with the object name(key) it’ll return the value associated with the key.

Conclusion

In this tutorial, we have learned how to use object literals in effective methods. However, writing conditionals will always be personal and it have different approaches. As form my view object literals are better in performance as well as in clean coding.

Quote of the Day

“The best error message is the one that never shows up.” — Thomas Fuchs

Thanks for reading! happy coding

Sign up to discover human stories that deepen your understanding of the world.

--

--

Kailas Pk
Kailas Pk

Written by Kailas Pk

Software engineer | Crypto enthusiast

No responses yet

Write a response