A Quick Guide to writing Cleaner code in Javascript

ยท

2 min read

A Quick Guide to writing Cleaner code in Javascript

Write Clean code and you can sleep well at night - James Richman

Writing clean code is very important as you are not writing code just for the machine but also for your later self, and your co-workers.

Most of the tips mentioned below are not limited to Javascript and can easily be transferred to any other programming language.

1. Use Meaningful Variable Names

Names assigned to variables should be meaningful and should describe what they represent. Multiple parts should follow the camelCase rule and constants should be named in ALLCAPS.

2. Avoid Nested Code

Nested code is hard to understand. Resort to writing as much linear code as possible. Linear code not only looks clean but is also easy to maintain.

3. Lesser arguments to a function

Functions should not have more than 3 parameters as it makes testing your function very difficult. Usually, if you have more than two arguments then your function is trying to do too much.

4. Avoid using Callbacks

Callbacks can be very difficult to read and maintain especially when they are nested. Prefer using promises or async/await wherever possible.

5. Use Destructuring

It is better to just import the functions you need to use in your file instead of the whole module, and then access it. Similarly, when you decide that you definitely need an object as a function parameter, use destructuring as well.

6. Use Extensions

Extensions will make your life easier. I recommend using Es-lint and Prettier to make sure your code is formatted and looks clean.

I hope these tips help you write cleaner code. Tell me about some best practices that you guys follow to write cleaner code in the comments below ๐Ÿ‘‡

Also, you can follow me on Twitter to learn more about my coding journey:

twitter.com/anuragrathod2

ย