DEV Community

Captain Iminza
Captain Iminza

Posted on

Clean JavaScript Code

We all just code but do not know how to arrange our work and components so that even the non-programmers can understand our work this is what is called 'clean code.'
Ways of writing clean JavaScript Code:
Variables
1.Use meaningful and pronounceable variable names
2.Use the same vocabulary for the same type of variable
3.Don't add unneeded context
4.Use explanatory variables
Functions
One should limit the number of functions in order to make testing easier. One should not use more than three parameters.
1.Functions should do one thing. When functions do more than one thing, they are harder to compose, test, and reason about.
2.Function names should say what they do
3.Remove duplicate code. Duplicate code is bad because it means that there's more than one place to alter something if you need to change some logic.
4.Don't write to global functions
Polluting global is a bad practice in JavaScript because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production.
5.Encapsulate conditionals
6.Avoid negative conditionals

Objects and Data Structures
1.Use getters and setters
Using getters and setters to access data on objects could be better than simply looking for a property on an object.
Makes adding validation simple when doing a set.
Encapsulates the internal representation.
Easy to add logging and error handling when getting and setting.

Dependency Inversion Principle (DIP)
This principle states two essential things:
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend upon details. Details should depend on abstractions.
Don't ignore caught errors
Doing nothing with a caught error doesn't give you the ability to ever fix or react to said error. Logging the error to the console (console.log) isn't much better as often times it can get lost in a sea of things printed to the console. If you wrap any bit of code in a try/catch it means you think an error may occur there and therefore you should have a plan, or create a code path, for when it occurs.

Comments
Only comment things that have business logic complexity.
Comments are an apology, not a requirement. Good code mostly documents itself.

Top comments (0)