Shibyan Riaz
Senior Frontend Dev

Follow

Senior Frontend Dev

Follow

Write Clean Code In JavaScript: Comments and Formatting

Don't fuck your code: Part 2

Shibyan Riaz's photo
Shibyan Riaz
·Aug 15, 2022·

7 min read

Write Clean Code In JavaScript: Comments and Formatting
Play this article

If you think that more comments in code are about better code then think again. Proper code writing and formatting(i.e., better naming conventions, adding blank lines, keeping lines short, etc.) make code more understandable than writing unnecessary comments. But this doesn't mean that comments are useless and shouldn't be a feature available in a programming language. For seeing their usefulness let's find the difference between good comments and bad comments.

Let's start with the evil one.

Bad Comments

So here, "bad" mostly refers to a "redundant", "confusing" or "misleading".

Markers and Dividers


// !!!!!!
// FUNCTIONS
// !!!!!!

function isValid(){...}

function getData(){...}

// !!!!!!
// DOM RENDERING
// !!!!!!

<div>
  <h1> Look <h1>
  <p> If you are a developer you can obliviously understand this is a  DOM HTML code   
          without needing any comment.
  </p>
</div>

Markers and dividers are unnecessary. If your code is organized and well-written (i.e., use proper names, etc.), then it is obvious what code part is about what.

You don't need extra makers for telling the obvious things. They create a hindrance in reading the code flow and make analyzing the code file hard and more time taking.

Redundant Information

function deleteProduct() { // deleting a product
  ...
}

Comments like the above add no value to the code. Instead, code readers stop and waste time reading redundant information. The above comment could be useful if the function would have a bad name like:


function remove() { // deleting a product
  ...
}

So better use proper naming conventions instead of writing comments like above. Avoid poor naming to avoid unnecessary comments.

Commented Out Code


function deleteProduct() {
  ...
}

// function addProduct() {
//  ...
// }

You might have done this many times. But you shouldn't. Instead, delete it or put it in a separate file(which contains all commented codes). As commented-out code only complicates reading through your code file by adding clutter.

A source control (like Git) can also be useful in reviving old code, so you don't have to fill your code file with commented code that even might not be needed in the future.

Writing HOW instead of WHY?


// adding Bearer prefix to a token string
// using local storage to save authToken 
function saveAuthToken(jwt) {
    const authToken = "Bearer" + jwt; 
   localStorage.setItem("authToken", authToken);
}

In the above example, instead of commenting how you should comment why for the code. If the developer doesn't know how the code works he can check that on google but telling why saving auth token in local storage is helpful in our application, can't be answered on google because that is application specific.

You will find how to write why for the code in the below good comments section.

Misleading Comments


function login() { // create a new user
  ...
}

The worst comments are probably those that really mislead the reader. As in the above function, the actual work of the function is totally apart from what was mentioned in the comment.

As this will confuse the reader and reader has to dive into the function completely(and any other functions it might call). Do the good by avoiding them.

Good Comments

Although comments don't make your code better, a couple of them are helpful if used wisely.

Warning

Warnings in some scenarios can help readers - for example, if some function code is incomplete and will not work(or break) for some scenario(or environment) then mentioning that would be worthwhile


function deriveWindowSize(){
  // WARNING: won't work in safari
  ...
}

Now you can also search your whole codebase for warning by the 'WARNING' keyword before pushing it to production.

Todo Notes

Whenever some feature is incomplete or in incremental steps, then you can add 'TODO' to remind yourself later or let others know about it.


function saveUser(userDetails) {
  // TODO: validate user details 
  ...
}

But you shouldn't over depend on it and always try to complete the feature whenever necessary.

In some projects and/ or companies, you would be asked to add legal information to your code files. Like:


// (c) Umbrella Corp.

So just add such information comment at the top of the code file as that wouldn't harm any reader much.

Required Explanations

Sometimes, you write some complex code that can't be verbose itself or will take more time for a reader to understand it (even from google). Then in that case giving a one-line explanation can make a difference. Like regular expressions:


// Min. 6 characters, at least: only one special character, one letter and one number
const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?
&]{6,}$/

In the above example, the naming convention is all fine, but still, the reader would be needing extra information as regular expressions are complex to decode.

Vertical Formatting

Vertical Formatting adds more readability to the code by grouping related concepts together and unrelated concepts apart by adding little vertical space(blank line) between them. But how one would decide where to add a blank line and where to not? That's determined by Vertical density and Vertical distance. Still with me? Let's dive further.

Vertical Density

It means that function/methods, statements, etc. that are related to each other should be kept nearby.

Vertical Distance

It means that there should be a space when some new concept or a little different concept starts in your code.

Example of Vertical Distance and Vertical Density


function login(email, password) {
 if (!email.includes('@') || password.length < 6) {
 throw new Error('Eat more almonds!');
 }

 const user = fetchUser(email, password);
 user.getRedirectPath();
}

Now, in the above code getting the user and redirecting the user are grouped together (Vertical Density) because they are somehow related. But the email-password validation and the user fetch-redirect they are having a blank line(Vertical Distance) in between because they have little different concepts.

These grouping and distancing applicable to functions / classes/ variable / statement etc.

Ordering Functions & Methods

If functions are calling each other then their definition should be nearby (try not to add other functions' definitions in between). Also known as the "step-down rule".

Divide Code Into Separate Files

If your codebase has multiple code concepts (like multiple classes) then try to divide code into multiple files to achieve more modularity and readability.

Horizontal Formatting

Horizontal Formatting is about making every code line more readable. The primary ways to achieve them are listed below.

Space Between Operator and Operands

Having space between operator and operand makes code clear and readable. Understand from the below example.


function display(msg, timeStamp) {
  const preMsg = `At ${timeStamp}, Here is you message: `;
  console.log(preMsg + msg);
}

In the above code, (msg, timestamp) has space as there should be space between an operator(,) and operand(timeStamp). On the 1st line of a function definition, there is a space before and after the equals-to(=) operator and on the 2nd line, there is space between preMsg and msg variable as they have a plus(+) operator in between.

Now, imagine the above function without such spacing.

Prefer Short Names

Names should be descriptive but shouldn't be unnecessarily long and too specific.


function SaveUserByMobileNumberAndEmail() {
....
}

function saveUser() {
...
}

Now think to yourself which one would be easier to read and which is unnecessary or too specific.

Breaking Code Into Multiple Lines

Try to break code in multiple lines instead of trying to write the whole code in line. One-liner code becomes hard to understand and also hard to edit at a later time.


const isEmailValid = (email) => !isEmpty(email) ? (isEmailFormatted(email) ? true : false) false;

Now, is the above code easier to understand or easier to add changes at a later time? Even readers might be needed to do extra horizontal scrolling too.


function isEmailValid(email) {
  if (!isEmpty(email)) {
    if (isEmailFormatted(email)) {
      return true;
    }
  }

  return false;
}

Now, this code is more easy to understand and easy to edit at a later time.

Conclusion

Comments can helpful if written with the intention of Why not with How. Your code should get a reason why and how can be found on google. Formatting really helps in understanding and editing code at a later time. Well, the next part of this series will be posted soon. It is good to get specialized in the frontend knowledge so please follow and stay tuned for that.

 
Share this