Curly Braces
If there is a block then we use curly braces. We should use a space before the bracket like this:
So do we have to use curly braces if there is one conditional line?
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.
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)
Vertical indents: empty line for splitting codes into logical blocks
Even a single function can often be divided into logical blocks.
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:
Option-2:
Function placement
The most preferable method is code first then function
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)
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.