How to write a clean code in JavaScript

Writing Clean Code Makes You More Productive.

Shiori Soma
6 min readFeb 21, 2021
Photo by Clément Hélardot on Unsplash

Why Clean Code

It is essential for Professional web developers to write “readable” code.

If you are a beginner in writing code, You might be so busy writing that you don’t even think about writing nicely. I have a experience that I wrote it up in a few days, but when I read it later, I couldn’t understand it. You might have similar experiences.

To tell you the truth, the one I mentioned above is about HTML and CSS. Although both HTML and CSS, it can be the same no matter who write it since there is one way to write. All you need to care about is the composition. On the other hand, JavaScript doesn’t have a strict rule, but it has many way to write. Some developers write codes a lot, others may write with only one line. That’s why it’s important to write according to the conventions to make it readable for everyone.

The program, which has clients like Web application, is not over once you write. There is always the possibility of changes such as fixing bug or adding/updating code according to requirement that have occurred. At this time, it is important to write clean(i.e. highly readable) code so that you don’t lose track of what you were trying to do when you read the code later.

Major Coding Conventions for JavaScript

However, it may be difficult to imagine a “clean code” in one word. At this time, I recommend you to be aware of coding conventions. Coding convention is a set of rules for writing unified code, such as naming for variables, how to add spaces and indentation, and how to write comments.

The following coding conventions have been published for JavaScript. Each of conventions are laid down for making clear how to write clear and readable code.

JavaScript style guide (MDN)
Google JavaScript Style Guide
Airbnb JavaScript Style Guide
Node.js Style Guide
JavaScript Style Guide (jQuery)

There are some contradictory conventions set forth here, so please take it as one of guidelines.

These are the basics, so you may already know and use them. Or, like me, you may not know what it is and just use it. I recommend that you look at these website every time you get lost. In addition, if you still can’t figure it out, you can ask someone.

JavaScript style guide

In this section, I pick up some conventions from JavaScript style guide (MDN) as an example. Just make sure that this is a rule, not a syntax regulation.

1.Blank Space

・The basic indentation is two spaces. Don’t use tabs.
・Put a space after comma or semicolon.
・Binary operators should be separated by spaces.
・Do not put spaces at the end of lines!
・Use blank lines to separate before/after definition blocks like functions, objects, etc.

— here is a blank line —
function valueObject(aValue) {
return aValue + 10;
}
— here is a blank line —
console.log(valueObject(5));
— here is a blank line —
//
15

For example, I used “tabs” for indentation so far because it is easier that I type one key for the tab. But as you can read, it had better to be “two spaces”(or sometimes four spaces). Why — because a tab could be a different number of columns depending on your environment, but a space is always one column.

One advantage of spaces over tabs is that spaces allow more flexible configurations of indents than the tab symbol. -JAVASCRIPT.INFO-

2.Coding Style

・The maximum line length should be agreed upon at the team-level. It is usually 80 or 120 characters.

・In inline functions or objects, put a space before and after the curly brackets, except before commas and semicolons.

Bad:

function valueObject(aValue) {return {key: aValue };}

Good:

function valueObject(aValue) {
return { key: aValue };
}

Always put “else” on a single line.

if (a < 10) {
console.log(“You are too young.”);
} else {
console.log(“You can come.”);
}

You don’t want to break lines?
There is another way to write If statement in one line as follows.

(a < 10) ? console.log(“You are too young.”) : console.log(“You can come.”);

・Do not use “else” after “return”.

if (x < y)
return -1;
if (x > y)
return 1;
return 0;

The execution of the function will be terminated immediately upon calling return. This means that you need to put If statement again after use “return”. At least you cannot use “else”.

3.Naming Conventions

・For Variable or Function names, use camel case format. First letter should be lowercase.
・Constant names are in all-caps underscore format.
・For Constructor(Class) names, use camel case format. First letter should be uppercase.

Variable/Function:
— -> lowerCase

Constant:
— -> UPPER_CASE

Constructor(Class):
— -> UpperCase

Here is the reason why you should start with lowercase letters for variable or function names. There is a rule that all “constants” that cannot be changed later must be “uppercase”.

・Private members should start with “_”.
・Event Handler Function should start with “on”.

Private members:
— -> _internalFunction

Event Handler:
— -> onLoad, onDialogAccept, onDialogCancel

4.Others

These may be a little different from how to write clean code, but they are also important to keep in mind.

・Make sure there is no duplicates of variable declaration.
・Use [value1, value2] for making JavaScript Array.
・Use { key: value } for making JavaScript Object.
・Do not compare boolean values to true/false.

The last item is difficult to understand, so I made a table.
Undefined, null, NaN, and “ ” are not equal in comparison with false, even though they are false. Therefore, neither true nor false should be compared to check the truth value.

You want to learn more about readable code?

Google JavaScript Style Guide

Here you are. I summarize the main points of “Google JavaScript Style Guide” without duplication of listed above.

By reading this section you will get more information. I’ve attached links to each item, so check them out if you want to know more!

・JS File names must be all lowercase.

If you use a combination of uppercase and lowercase letters, it must be strictly coherent. Why — because when you jump from a case-insensitive server to a case-sensitive server, even a small error can break your web site. To avoid these problems, always use lowercase filenames if possible.

・Every statement must be terminated with a semicolon.

However, it is also true that there is a group of people who do not use semicolons. For me, my programming teacher told me I need to put semicolon all the time but I put a semicolon case by case. Sometimes I’m still confused like when I use a function.

You might be able to find answer in this article. Or if you are confused how to use it like me, may find the answer in this forum.

・String literals are delimited with single quotes ('), rather than double quotes (").

I prefer to use double quotes because it is easier to recognize at a glance. However, single quotes are recommended in Google’s JavaScript coding conventions. The reason is that single quotation marks are more convenient when creating strings containing HTML.

Wrapping Up

Now, you know what is clean code and how to write code clean. By following these conventions, you will be able to write code that is at least not “dirty”. Furthermore, your code will be outrageously easy to read for not only yourself but also everyone. You know, “clean code” is “readable code”.

Writing readable code is the same as writing code that is friendly to others. Writing highly readable code make preventing bugs and it can be fixed quickly, thus increasing maintainability in the long run. This will affect productivity in the end.

Let me remind you again, you don’t have to follow this completely because there must be a contradiction in the rules. Do not forget that the most important thing is to adapt to the people you are working with.

Writing clean code makes you more productive.

I hope you have fun writing code. Enjoy!

--

--

Shiori Soma

I’m a front-end web developer based in Vancouver, studying CICCC, an web and mobile app development course. https://shiory602.github.io/portfolio/