Stop Using Conditional Statements Everywhere in JavaScript, Use an Object Literal instead

Photo by Pankaj Patel on Unsplash

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.

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.toLowerCase()){
case 'cat': return 'Kitten'
case 'cattle': return 'Calf'
case 'cheetah': return 'Cub'
case 'dog': return 'Pup'
default: return "I don't know that"
}
const babyAnimal = {
cat:'Kitten',
cattle:'Calf',
cheetah:'Cub',
dog:'Pup'
}
return babyAnimal[animal.toLowerCase()] ?? "I don't know that"

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store