Creating maintainable JavaScript code is important if want to keep using the code.
In this article, we’ll look at the basics of creating maintainable JavaScript code by improving formatting.
Line Length Conventions
There’re various line length conventions we can use as guidelines to come up with our own conventions.
Java’s style guide specifies 80 characters as the max length of a line.
The Android style guide specifies 100 characters.
Ruby specifies 80 characters.
Python specifies 79 characters.
Therefore, around 80 to 100 is probably a suitable length for a line.
Line Breaks
When a line reaches a maximum length, then we’ve to split them into 2 lines.
If a line is a continuation of the previous line, then we indent it.
For instance, we can write:
callAFunction('foo', 'bar', window, document, true, 123,
navigator);
We indent the continuation of the first line with 2 spaces so that we can see the indentation.
This way, we know the 2nd line is actually th continuation of the first line.
The comma stays in the first line for more clarity.
We should use the same convention for statements.
For instance, we can write:
if (isLeapYear && isFebruary && day == 29 && isBirthday &&
hasNoPlans) {
wait4Years();
}
We also have an indent in the boolean expression we passed into the if
statement.
The &&
operator stays in the first line.
The assignment of variables can be indented the same way.
For example, we can write:
let result = something + anotherThing + anotherThing +
somethingElse + oneMoreThing + anotherSomethingElse;
to indent the code the same way.
Blank Lines
Blank lines are useful for grouping bunch of code together,
We can make our code clearer by inserting some blank lines between the groups.
For example, we can write:
if (wl && wl.length) {
for (i = 0, l = wl.length; i < l; i++) {
p = wl[i];
type = Y.Lang.type(r[p]);
if (s.hasOwnProperty(p)) {
if (merge && type == 'object') {
Y.mix(r[p], s[p]);
} else if (!(p in r)) {
r[p] = s[p];
}
}
}
}
We have all the code bunched together which makes them hard to read.
Instead, we can write:
if (wl && wl.length) {
for (i = 0, l = wl.length; i < l; i++) {
p = wl[i];
type = Y.type(r[p]);
if (s.hasOwnProperty(p)) {
if (merge && type == 'object') {
Y.mix(r[p], s[p]);
} else if (!(p in r)) {
r[p] = s[p];
}
}
}
}
We have some extra blank lines in if
and for
statements so that we can read them easier.
A good convention for adding blank lines would be:
- between methods
- between local variables and methods and its first statement
- between comments
- between logical sections in a method
They all make our code easier to read.
Conclusion
We can make our code easier to read by indenting our line continuation and add some line breaks.