Tips to declutter your JavaScript code

Photo by Clément H on Unsplash

Less lines of code doesn’t necessarily mean it is easy to understand for other developer to read. Making a code easy to read and understand is what every developer should aim for, and to me that is one of the better qualities of a good developer.

I understand, we thrive to write clean code and sometimes it comes at the price of readability, but that doesn’t have to be the case at all times. e.g I wrote a small article to simplify if-else blocks it looks clean and concise while maintaining readability.

In this post I’ll try to add a few tips as well which will try to achieve the aforementioned result. As always writing code is an art which evolves through practice and as any art form it is unique to the individual who wrote it.

I have used Typescript for the below example.

Making use JavaScript Objects to avoid if-else and switch statements
e.g. The below code receives a key and returns the corresponding month name. You can either use switch or if-else-if blocks to achieve this as shown. This works alright for a smaller size of the list, but what if the there are 50 or 100 values which you need to cater for.

That’s when the you should use JavaScript Objects.
Have a look at the below code. It’s super concise and does exactly the same thing as the previous snippet. In my opinion its elegant and doesn’t cause readability issues as well.

Use Objects to avoid conditionals

Give it a go next time you write an if else or switch statements. You’ll appreciate it.

--

--

--

Frontend Lead @creditorwatch

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

Recommended from Medium

Congrats to JS Chapter finishers!

Random Creations : Week 1 — Android Random List App + 3D Renders

Let’s dive into the React js

https://youtu.be/QCjrDID8L1o

Introducing Advanced Angular Component Patterns

//platform.twitter.com/widgets.js from Twitter https://twitter.com/DaveBuysOrlando

Sync and async fs

Coding for Scrubs: Anagram Palindrome (JS)

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
Arun Baghel

Arun Baghel

Frontend Lead @creditorwatch

More from Medium

The JavaScript Promise — To Resolve or To Reject

Javascript Array Methods You Must Know

Common Array Operations in JavaScript

Object in JavaScript