Stop Using Conditional Statements Everywhere in JavaScript, Use an Object Literal instead
2 min readOct 22, 2021
Conditional Statements (If-Else, Switch) can be easily replaced with Object Literals. They make the code better.
Object Literals
An Object Literal is one of the most popular and widely used pattern to define objects in JavaScript. It is a collection of key-value pairs. JavaScript being powerful, adds some additional functionalities to the simple objects through object literals.
const obj = {
first_name: 'Neelesh',
last_name: 'Arora'
}// An example of an object literal
How can we use Object Literal as a replacement to Conditional Statements?
Let us consider an example scenario to understand this.
A user enters an animal, we need to return the name of its baby (what is is called).
Look at the following codes:
if(animal.toLowerCase()==='cat'){
return 'Kitten'
} else if(animal.toLowerCase()=='cattle'){
return 'Calf'
} else if(animal.toLowerCase()==='cheetah'){
return 'Cub';
} else if(animal.toLowerCase()==='dog'){
return 'Pup';
} else{
return "I don't know that"
}switch(animal.toLowerC…