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

Photo by Pankaj Patel on Unsplash

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?

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"

--

--

--

Software Engineer | Full Stack / Back-end Developer | https://neelesharora.in

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Javascript (Java) Applied to Digital Marketing Businesses

React state management with React Recoil

What I learned from Googling WebSockets for 3 Hours

XR Technology Stacks, Options and Solutions

Setup AWS instance and Deploy ReactJs App on AWS Part-1

JAMstack Basics: How to Create a Gatsby Starter with Contentful and Deploy to Netlify

Connecting MongoDB to Express

The Spread Operator & Arrays

console.log of array data, they are identical

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
Neelesh Arora

Neelesh Arora

Software Engineer | Full Stack / Back-end Developer | https://neelesharora.in

More from Medium

4 most important features coming in ES2022 that you should know about

5 Front-End Development Trends for 2022

11 Useful Modern JavaScript Tips

Best VS Code Extensions in 2022