JavaScript Coding Conventions and Style Guides
2020-09-25 18:01:00 | | Part 2 of 5
Tested On
- Linux Ubuntu 20.04
- Windows 10
- macOS Catalina
Before we write too much code, I strongly recommend you follow a Javascript style guide, as it makes your code more readable to the general JavaScript community. For better or worse, coding conventions are a heated topic of debate within the programming community. And no matter how strongly you feel about your stylistic choices, you'll probably end up at a company that will force you to adopt their standards to keep code consistent and easy to maintain.
Regardless, you have to start somewhere, and I recommend Crockford's style guide. I'll also list some of what I prefer, below. Style guides give you a strong foundation to form your own opinionated style, and something you will research and experiment with for the rest of your programming career.
Understanding Coding Conventions Without Knowing How to Code
Because this is an introductory article, you may not understand all of the code presented to you. It's basically the chicken or the egg problem. My recommendation is that you skim through, and bookmark this page to refer to in the future. This growing list highlights my preferences, after writing JavaScript for 10+ years. Most of them are designed to help you avoid buggy scenarios that result from the JavaScript just-in-time interpreter compiling your code. For the rest, I provide logical arguments that are, again, influenced by my own experience as a developer. Let's get right to it.
Indentation Should Use 4 or 2 Spaces Per Indentation level
When I write Python, I go with 4 spaces, but I personally prefer 2 spaces, when writing JavaScript, HTML, and CSS. These files tend to have more indentation levels because of JavaScript's callback hell, HTML's nested DOM elements, and CSS's media queries. It's just more convenient to have as much screen real estate before code starts wrapping to the next line. With that being said, even if you learn to avoid callback hell in your own code, you will probably run into it in your co-workers' code. Be prepared. This is what callback hell looks like, by the way. Do not write code like this!
function fetchRecords(successCallback) {
xhr = new XMLHttpRequest();
xhr.open('POST', 'path/to/service');
xhr.onload = function() {
if (xhr.status === 200) {
try {
formatResult(xhr.responseText, function(result) {
saveResult(xhr.responseText, function(formatted) {
successCallback(formatted);
})
})
} catch(err) {
errorCallback(err);
}
}
else if (xhr.status !== 200) {
errorCallback(xhr.responseText);
}
};
xhr.send();
}
Speaking of hell, there's a special place in it for people who use 3 spaces.
Start Your Curly Brace on the Same Line and End on the Next Line
Hopefully, that makes sense. See below for an example.
I prefer this:
function hello() {
console.log('Hello world!');
}
Not this:
function hello()
{
console.log('Hello world!');
}
Although it's slightly easier to match curly brace indentation levels with the 2nd example, I still prefer the 1st because it keeps my code more compact and with fewer lines to scroll through. Most of my code are compact functions without a lot of nesting, anyway, and I have syntax highlighting to indicate matching curly braces.
Always Use Curly Braces and Semicolons
I always use curly braces because some debuggers will not stop on the inside the brace-less if statement. I also use them because not doing so breaks some documentation generators. It's also more readable. As for semicolons, because JavaScript will auto-insert them when they are missing and certain scenarios will produce bugs. Better to save yourself the debugging time, and explicitly insert them.
I prefer this:
if (flag === true) {
return 'Found';
}
return 'Not found';
Not this:
if (flag === true)
return 'Found'
return 'Not found'
Use Blank Spaces to Group Meaningful Blocks of Code
Similar to breaking up sentences into paragraphs, I normally add a line of whitespace after declaring variables and conditionals. I also put my return statements on their own whitespace-separated line.
I prefer this:
function setCookie(name, value, days){
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/; domain=codeboxsystems.com";
}
Not this:
function setCookie(name, value, days){
var expires = '';
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toUTCString();
}
document.cookie = name + '=' + (value || '') + expires + '; path=/; domain=codeboxsystems.com';
}
Use Single Quotes Whenever Possible
In the past, I would use a combination of both double and single quotes—single quotes for Object keys and double quotes for strings (letters and phrases). Now, I use single quotes 99% of the time because holding the shift key is not ergonomic and slows down typing. I only use double quotes when I have to wrap something that contains a single quote (like an apostrophe).
I prefer this:
var name = 'John';
var response = 'User not found';
var message = "User's new password is invalid";
Not this:
var name = "John";
var response = "User not found";
var message = 'User\'s new password is invalid';
Conclusion
That concludes this tutorial. As you continue along your JavaScript career path, you'll develop your own preferences. You might even strongly advocate for certain best practices. We'd love to hear about them in the comments, so please share.
If you're interested in making interactives and games, we recommend you take our Learn JavaScript While Building a Game Framework course, which teaches you JavaScript and ES6 while you build an HTML5 Canvas, physics-based framework, from scratch. You'll also learn drag and drop, mouse following, velocity, acceleration, friction, and many other useful functionality you can build interactives and games with. In addition, it compiles into a browser-compatible ES2015 build. Start making canvas applications, today.
Comments
You must log in to comment. Don't have an account? Sign up for free.
Subscribe to comments for this post
Info