I’ve recently created a JavaScript Quality Guide, and I wanted to share it on Pony Foo as well. The latest version can be found on GitHub. As all-things-style-guides go, it’s super opinionated so take it with a pinch of salt.

This style guide aims to provide the ground rules for an application’s JavaScript code, such that it’s highly readable and consistent across different developers on a team. The focus is put on quality and coherence across the different pieces of your application.

Modules

This style guide assumes you’re using a module system such as CommonJS, AMD, ES6 Modules, or any other kind of module system. Modules systems provide individual scoping, avoid leaks to the global object, and improve code base organization by automating dependency graph generation, instead of having to resort to manually creating tens of <script> tags.

Module systems also provide us with dependency injection patterns, which are crucial when it comes to testing individual components in isolation.

Strict Mode

Always put 'use strict'; at the top of your modules. Strict mode allows you to catch non-sensical behavior, discourages poor practices, and is faster because it allows compilers to make certain assumptions about your code.

Spacing

Spacing must be consistent across every file in the application. To this end, using something like .editorconfig configuration files is highly encouraged. Here are the defaults I suggest to get started with JavaScript indentation.

Settling for either tabs or spaces is up to the particularities of a project, but I recommend using 2 spaces for indentation. The .editorconfig file can take care of that for us and everyone would be able to create the correct tabs by pressing the tab key.

Spacing doesn’t just entail tabbing, but also the spaces before, after, and in between arguments of a function declaration. This kind of spacing is typically highly irrelevant to get right, and it’ll be hard for most teams to even arrive at a scheme that will satisfy everyone.

function(){}

function( a, b ){}

function(a, b){}

function(a,b){}

Try to keep these differences to a minimum, but don’t put much thought to it either.

Semicolons;

Automatic Semicolon Insertion (ASI) is not a feature. Don’t rely on it. It’s super complicated and there’s no practical reason to burden all of the developers in a team for not possessing the frivolous knowledge of how ASI works. Avoid headaches, avoid ASI.

Always add semicolons where needed

Style Checking

Don’t. Seriously, this is super painful for everyone involved, and no observable gain is attained from enforcing such harsh policies.

Linting

On the other hard, linting is sometimes necessary. Again, don’t use a linter that’s super opinionated about how the code should be styled, like jslint is. Instead use something more lenient, like jshint or eslint.

A few tips when using JSHint.

Declare a .jshintignore file and include node_modules, bower_components, and the like

You can use a .jshintrc file like the one below to keep your rules together

By no means are these rules the ones you should stick to, but it’s important to find the sweet spot between not linting at all and not being super obnoxious about coding style.

Strings

Strings should always be quoted using the same quotation mark. Use ' or " consistently throughout your codebase. Ensure the team is using the same quotation mark in every portion of JavaScript that’s authored.

Bad

var message = 'oh hai ' + name + "!";

Good

var message = 'oh hai ' + name + '!';

Usually you’ll be a happier JavaScript developer if you hack together a parameter-replacing method like util.format in Node. That way it’ll be far easier to format your strings, and the code looks a lot cleaner too.

To declare multi-line strings, particularly when talking about HTML snippets, it’s sometimes best to use an array as a buffer and then join its parts. The string concatenating style may be faster but it’s also much harder to keep track of.

With the array builder style, you can also push parts of the snippet and then join everything together at the end. This is in fact what some string templating engines like Jade prefer to do.

Variable Declaration

Always declare variables in a consistent manner, and at the top of their scope. Keeping variable declarations to one per line is encouraged. Comma-first, a single var statement, multiple var statements, it’s all fine, just be consistent across the project, and ensure the team is on the same page.

Bad

var foo = 1,
bar = 2;
var baz;
var pony;
var a
, b;

var foo = 1;
if (foo > 1) {
var bar = 2;
}

Good

Just because they’re consistent with each other, not because of the style

var foo = 1;
var bar = 2;
var baz;
var pony;
var a;
var b;

var foo = 1;
var bar;
if (foo > 1) {
bar = 2;
}

Variable declarations that aren’t immediately assigned a value are acceptable to share the same line of code.

Acceptable

var a = 'a';
var b = 2;
var i, j;

Conditionals

Brackets are enforced. This, together with a reasonable spacing strategy will help you avoid mistakes such as Apple’s SSL/TLS bug.

Bad

Good

Ternary Operators

Ternary operators are fine for clear-cut conditionals, but unacceptable for confusing choices. As a rule, if you can’t eye-parse it as fast as your brain can interpret the text that declares the ternary operator, chances are it’s probably too complicated for its own good.

Bad

Good

Good

var plusThree = sum.bind(null, 3);

Keep in mind that function expressions will be hoisted to the top of the scope so it doesn’t matter the order they are declared in. That being said, you should always keep functions at the top level in a scope, and avoid placing them inside conditional statements.

Better

Whenever a method is non-trivial, make the effort to use a named function expression rather than an anonymous function. This will make it easier to pinpoint the root cause of an exception when analyzing stack traces.

Good

console statements

Preferrably bake console statements into a service that can easily be disabled in production. Alternatively, don’t ship any console.log printing statements to production distributions.

Comments

Comments aren’t meant to explain what the code does. Good code is supposed to be self-explanatory. If you’re thinking of writing a comment to explain what a piece of code does, chances are you need to change the code itself. The exception to that rule is explaining what a regular expression does. Good comments are supposed to explain why code does something that may not seem to have a clear-cut purpose.

Bad

Good

Polyfills

Where possible use the native browser implementation and include a polyfill that provides that behavior for unsupported browsers. This makes the code easier to work with and less involved in hackery to make things just work.

If you can’t patch a piece of functionality with a polyfill, then wrap all uses of the patching code in a globally available method that is accessible from everywhere in the application.

Everyday Tricks

Use || to define a default value. If the left-hand value is falsy then the right-hand value will be used.

Comments(5)

Chapter: “Functions”. I don’t get it: it’s written: “When declaring a function, always use the function expression form instead of function declarations.” but below is an example of function expression marked as “Bad”?

As mentioned by cachaito, the authors understanding of function expression vs function declaration is wrong. The author has it backwards. The statement “Keep in mind that function expressions will be hoisted to the top of the scope” is wrong. Function declarations are hoisted, not function expressions.

Function Expression: var what = function () {}; // the function is in the expression position…where you define the value

Function Declaration: function what() {} // the function is in the declaration position…like a variable declaration

With a function expression, the variable name is hoisted with the value undefined. The expression value is assigned to the variable when the script execution reaches the assignment in the code. With a function declaration, the function is hoisted with it’s value.

The link the author provides explaining a function expression is correct. You can assign a name to a function expression too…