5 Best practices for Clean Code every Javascript developer should know
Do you want to be more motivated when working on your projects, impress your code reviewer and take your development to a whole other level, you should start writing clean code.
The difference between making unreadable code and code as clear as the sky is not rocket science, on the contrary, it will only make programming easier.
Table of contents
Let’s understand Clean Code
What is Clean code?
Many developers still think that Clean code is all about writing as few lines as possible. But this is not entirely true. Clean code is all about making understandable code.
Clean code is not only concise code, but more importantly, it is readable. A rule of thumb when writing code, is to write code as if comments didn’t exist. The code should be self-explanatory.
Another part about clean code, which only the fewest developers talk about, is how the same code can be written in many different ways. This leaves a lot of room for confusion, especially in a Dynamic typed language like javascript. Truly clean code can’t be interpreted in multiple ways.
So… Clean Code is concise, self-explanatory, and can’t be interpreted in multiple ways.
Why do we need it?
There is no question that clean code can require more work and can take longer to write. But there is also no that, dirty and fast code is super unpractical in the long run…
Implementing, maintaining, and refactoring will be a challenge if you are working with unreadable code. your future self and/or other developers will need to spend a long time understanding what is going on in the code.
Learning clean code is the best productivity hack any developer can do!
#1: Better Naming
Despite we can’t change syntax, we still have full control over our variables. This is one of the best places we can improve our code. The key to good naming does not lie in having the shortest variable names, but rather in having the most descriptive ones.
No magic numbers
First of all, don't use magic numbers. Make sure that all numbers are stored in a variable, so that you know what the number accounts for. And if you are using a constant primitive (a primitive value that won’t change), you should name them in capital snake_case.
with magic numbers👎
without magic numbers👍
Name by type
In a dynamic language like javascript, you can easily get confused, when you can’t access the variable type. And a single variable can be interpreted in multiple ways, which leads to a lot of confusion when reading the code.
bad names👎
good names👍
#2: Keep it concise
Although naming arent about brevity, the general code is, to a certain extent. Many programmers lose track
Keep it DRY
To better achieve concise code, you should make sure to follow the DRY (Don’t Repeat Yourself) principle.
Repeated code👎
DRY👍
Single responsibility principle
With the Single responsibility principle, you can easily name your functions, which only do one thing. You know exactly what the function does by its name, and the function won’t be long and overwhelming.
the function does a lot of things👎
one purpose functions👍
Recursion can be more concise
The truth is that loop is a tiny bit more optimized, but if you are not working with IoT devices you will most likely not feel the difference. Recursions can be super concise and clean if done correctly!
Template Literals for String Concatenations
the template literals are shorter, cleaner, and allow for multi-line strings.
adding to string👎
const welcomeMessage = “Hi ” + user + “, today you need to “ + firstTodo
template literal👍
const welcomeMessage = `Hi ${user}, today you need to ${firstTodo}`
#3: Get rid of deep nesting
One of the easiest places to lose while reading code, is if you encounter deeply nested code inside of a bunch of different brackets. Try to keep your code as linear as possible, using the techniques below.
Use Guard Clauses
Don’t nest your return statement into an if-else. Get rid of the nesting & shorten the code with guard clauses.
without any guard clause👎
with a guard clause👍
Sometimes it is even possible to return with a ternery👍
Async await instead of promises
As soon as you have a set of chained promises, you will have nested code with bad readability.
promises👎
async await👍
#4: Destructure
You can spare a lot of code, by restructuring your objects and arrays. In the example below you can see how easy it is to extract, name, and provide fallback values, for restructured values.
destructuring👍
#5: Learn this syntax
Remembering syntax is not what programming is all about, but knowing the syntax below definitely bumps your ability to write clean code.
Optional changing & spread operator
without👎
with👍
get familiar with array functions and operators
Array functions allow for advanced iterations with a super compact syntax, which you can learn more about here.
Learning operators, like the bang, and, not, and the ternary and more, allows for much simpler operations.
Without using array functions and special operators👎
Using array functions and special operators👍
#Bonus advice
Have common best practices in your team
Clean code can look different from developer to developer, which means that the patterns and best practices will be different throughout the entire project.
So if you are working on a project with a team, I would encourage you to decide upon some fixed best practices, to make achieve a uniform structure in your codebase.
You can benefit from using Eslint, to better identify problematic patterns & unnecessary resources in the code. It can also help you with sticking to the decided coding patterns, and keeping the code uniform. And on top of that, you can add Prettier, to the project, and get your code auto-formatted.
#Clean code checklist
- The code should be self-explanatory & shouldn’t need comments.
- Better naming: No magic numbers & one-letter variables, descriptive names
- Keeping it concise: DRY, single responsibility principle, Template literal’s
- No deep nesting: Guard clauses, async-await
- Destructure: objects, arrays, arguments
- Get familiar with this concise syntax: optional chaining and spread operator, learn more operators and array functions
- Bonus advice: Agree on best practices in the team, and install Eslint and Prettier.
Feel free to leave a comment, if you have any other topics you would want to get an elaboration on.