Basic Formatting
Formatting our code is important for readability.
This is probably the first thing we’ve to think about when we’re wiring JavaScript code.
The suggested indentation is 2 spaces.
Spaces are portable between different platforms and text editors and so they’re consistent anywhere.
Most text editors will automatically fix formatting of our code files.
If not, then linters will help us fix them.
For example, we have 2 spaces for indentation in the following code:
if (wl && wl.length) {
for (i = 0, l = wl.length; i < l; i++) {
p = wl[i];
if (s.hasOwnProperty(p)) {
if (merge && type == 'object') {
Y.mix(r[p], s[p]);
} else if (p in r) {
r[p] = s[p];
}
}
}
}
A single tab character can be different from different platforms.
This means we’ve to configure tab spacing if we need to move between different platforms.
So opening a file with tabs may look different from different programs.
Therefore, multiple spaces are better for indentation.
We can change tabs to spaces automatically if we want to save some typing.
Different style guides may stipulate different kinds of spacing for our code files.
jQuery’s style guide treats indents as tabs.
Douglas Crockford’s code style guide specified indents as 4 spaces.
We can just stick with one and forget about it.
2 spaces save typing and it’s consistent everywhere so we can use that.
Statement Termination
JavaScript statements can be terminated with a newline or a semicolon.
This is different from other C-like languages which requires a semicolon.
We can skip the semicolon since JavaScript will insert it for us automatically.
That means the semicolon is actually required.
It’s just inserted automatically for us.
Therefore, it’s just better to insert it ourselves.
The rules for automatic semicolon insertion is hard to remember, so we shouldn’t both remembering them ourselves.
For example:
function getData() {
return
{
firstName: 'jane',
lastName: 'smith'
}
}
is probably a mistake since the return
statement would be added after the return
.
Instead, we write:
function getData() {
return {
firstName: 'jane',
lastName: 'smith'
};
}
so there’s no chance that we’ll make a mistake.
Limiting automatic semicolon insertion helps us reduce errors.
Errors are typically caused by the misunderstanding of automatic semicolon insertion.
Various linters like JSHint and ESLint will check for these errors and let us fix them.
Line Length
Line length also matters for maintainable JavaScript because we got to make reading the code easier.
Therefore, we won’t want to scroll horizontally to read each line of our code.
Many code conventions tell us the line of code shouldn’t be longer than 80 characters.
This is a convention that’s created when screens are small.
Today, we may be able to increase the length slightly to 100 characters or even more depending on how big our screens are.
Conclusion
Basic formatting is important for creating maintainable JavaScript code.
We got to make our code easy to read.