DEV Community

Cover image for How to make Javascript code neat and clean
Asikur Rahman
Asikur Rahman

Posted on

How to make Javascript code neat and clean

Curly Braces
If there is a block then we use curly braces. We should use a space before the bracket like this:
Alt Text
So do we have to use curly braces if there is one conditional line?
Alt Text
Well, using curly braces is safe and good practice but you can write without a curly brace if there is only one line in the condition.

Line length
No one likes to read along the horizontal line it’s better to split them into small lines.
Alt Text

Indents
There are two types of indents
Horizontal indents: 2 or 4 space
A horizontal indentation is made using either 2 or 4 spaces or the horizontal tab symbol(key Tab)
Alt Text
Vertical indents: empty line for splitting codes into logical blocks
Even a single function can often be divided into logical blocks.
Alt Text

Semicolons
A semicolon should be present after each statement, even if it could possibly be skipped.

There are languages where a semicolon is truly optional and it is rarely used. In JavaScript, though, there are cases where a line break is not interpreted as a semicolon, leaving the code vulnerable to errors.

Nesting level
Try to avoid nesting code too many levels deep.
For example, instead of adding a nested if/else we can use a return conditional like this:
Option-1:
Alt Text
Option-2:
Alt Text
Function placement
The most preferable method is code first then function
Alt Text
Summary
The main point of this writing is to make code readable. We should concern about that is our code readable and easy to understand.
We can read popular style guides to keep up to date about coding style trends and best practice.

Top comments (1)

Collapse
 
camelcaseguy profile image
Shubhendra Singh Chauhan

Hey @arraju these are really some good points to write clean and readable JS code. ✨

Speaking of style guides - you can actually set up popular code styles for your project by integrating DeepSource in your project. Whenever you or a contributor will push changes then issues will be raised if there's a violation of code style. Read more about it here.