This style guide aims to provide the ground rules for CFPB's JavaScript code, such that it's highly readable and consistent across different developers on a team.
- Linting
- Modules
- Strict Mode
- Spacing
- Naming
- Semicolons
- Strings
- Variable Declaration
- Conditionals
- Equality
- Ternary Operators
- Functions
- Prototypes
- Object Literals
- Array Literals
- Regular Expressions
consoleStatements- Comments
- Variable Naming
- Polyfills
- Everyday Tricks
- Credits
Lint your code using ESLint. CFPB-tailored ESLint options exist.
This style guide assumes you're using a module system such as CommonJS, AMD, ES6 Modules, or any other kind of module system. If you are using CommonJS, refer to the CommonJS guide for structuring your modules. 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 multiple <script> tags.
Module systems also provide us with dependency injection patterns, which are crucial when it comes to testing individual components in isolation.
Always put 'use strict'; at the top of your modules. Strict mode allows you to catch nonsensical behavior, discourages poor practices, and is faster because it allows compilers to make certain assumptions about your code.
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 we suggest to get started with JavaScript indentation.
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = falseWe 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 spacing 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. Try to keep this spacing consistent throughout the codebase.
Where possible, improve readability by keeping lines below the 80-character mark.
- Functions, variables, methods, objects and instances should be named using
camelCase. - Constructors and prototypes should use
PascalCase. - Symbolic constants should use
UPPERCASE. - Encapsulated (private) variables and methods should use
_underscoreCamelCase. - Prefix variables or properties that reference a jQuery object with
$or_$(depending on exposure). For example:var $button = $( '.btn-class' );.
We advocate for using semicolons at the end of each line. This choice is done to avoid potential issues with Automatic Semicolon Insertion (ASI).
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. In general, we prefer to use single quotation marks '.
var message = 'oh hai ' + name + "!";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.
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.
var foo = 1,
bar = 2;
var baz;
var pony;
var a
, b;var foo = 1;
if (foo > 1) {
var bar = 2;
}(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.
var a = 'a';
var b = 2;
var i, j;Brackets are enforced. This, together with a reasonable spacing strategy will help you avoid mistakes such as Apple's SSL/TLS bug.
if (err) throw err;if (err) { throw err; }It's even better if you avoid keeping conditionals on a single line, for the sake of text comprehension.
if (err) {
throw err;
}Avoid using == and != operators, always favor === and !==. These operators are called the "strict equality operators," while their counterparts will attempt to cast the operands into the same value type.
function isEmptyString (text) {
return text == '';
}
isEmptyString(0);
// <- truefunction isEmptyString (text) {
return text === '';
}
isEmptyString(0);
// <- falseTernary 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.
jQuery is a prime example of a codebase that's filled with nasty ternary operators.
function calculate (a, b) {
return a && b ? 11 : a ? 10 : b ? 1 : 0;
}function getName (mobile) {
return mobile ? mobile.name : 'Generic Player';
}In cases that may prove confusing just use if and else statements instead.
When declaring a function, always use the function declaration form instead of function expressions. Because hoisting.
var sum = function (x, y) {
return x + y;
};function sum (x, y) {
return x + y;
}That being said, there's nothing wrong with function expressions that are just currying another function.
var plusThree = sum.bind(null, 3);Keep in mind that function declarations 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.
if (Math.random() > 0.5) {
sum(1, 3);
function sum (x, y) {
return x + y;
}
}if (Math.random() > 0.5) {
sum(1, 3);
}
function sum (x, y) {
return x + y;
}function sum (x, y) {
return x + y;
}
if (Math.random() > 0.5) {
sum(1, 3);
}If you need a "no-op" method you can use either Function.prototype, or function noop () {}. Ideally a single reference to noop is used throughout the application.
Whenever you have to manipulate an array-like object, cast it to an array.
var divs = document.querySelectorAll('div');
for (i = 0; i < divs.length; i++) {
console.log(divs[i].innerHTML);
}var divs = document.querySelectorAll('div');
[].slice.call(divs).forEach(function (div) {
console.log(div.innerHTML);
});However, be aware that there is a substantial performance hit in V8 environments when using this approach on arguments. If performance is a major concern, avoid casting arguments with slice and instead use a for loop.
var args = [].slice.call(arguments);var i;
var args = new Array(arguments.length);
for (i = 0; i < args.length; i++) {
args[i] = arguments[i];
}Don't declare functions inside of loops.
var values = [1, 2, 3];
var i;
for (i = 0; i < values.length; i++) {
setTimeout(function () {
console.log(values[i]);
}, 1000 * i);
}var values = [1, 2, 3];
var i;
for (i = 0; i < values.length; i++) {
setTimeout(function (i) {
return function () {
console.log(values[i]);
};
}(i), 1000 * i);
}var values = [1, 2, 3];
var i;
for (i = 0; i < values.length; i++) {
setTimeout(function (i) {
console.log(values[i]);
}, 1000 * i, i);
}var values = [1, 2, 3];
var i;
for (i = 0; i < values.length; i++) {
wait(i);
}
function wait (i) {
setTimeout(function () {
console.log(values[i]);
}, 1000 * i);
}Or even better, just use .forEach which doesn't have the same caveats as declaring functions in for loops.
[1, 2, 3].forEach(function (value, i) {
setTimeout(function () {
console.log(value);
}, 1000 * i);
});Whenever a method is non-trivial, make the effort to use a named function declaration rather than an anonymous function. This will make it easier to pinpoint the root cause of an exception when analyzing stack traces.
function once (fn) {
var ran = false;
return function () {
if (ran) { return };
ran = true;
fn.apply(this, arguments);
};
}function once (fn) {
var ran = false;
return function run () {
if (ran) { return };
ran = true;
fn.apply(this, arguments);
};
}Avoid keeping indentation levels from raising more than necessary by using guard clauses instead of flowing if statements.
if (car) {
if (black) {
if (turbine) {
return 'batman!';
}
}
}if (condition) {
// 10+ lines of code
}if (!car) {
return;
}
if (!black) {
return;
}
if (!turbine) {
return;
}
return 'batman!';if (!condition) {
return;
}
// 10+ lines of codeHacking native prototypes should be avoided at all costs, use a method instead. If you must extend the functionality in a native type, try using something like poser instead.
String.prototype.half = function () {
return this.substr(0, this.length / 2);
};function half (text) {
return text.substr(0, text.length / 2);
}Avoid prototypical inheritance models unless you have a very good performance reason to justify yourself.
- Prototypical inheritance boosts puts need for
thisthrough the roof - It's way more verbose than using object literals
- It causes headaches when creating
newobjects - Needs a closure to hide valuable private state of instances
- Just use object literals instead
Instantiate using the egyptian notation {}. Use factories instead of constructors.
Instantiate using the square bracketed notation []. If you have to declare a fixed-dimension array for performance reasons then it's fine to use the new Array(length) notation instead.
Keep regular expressions in variables, don't use them inline. This will vastly improve readability.
if (/\d+/.test(text)) {
console.log('so many numbers!');
}var numeric = /\d+/;
if (numeric.test(text)) {
console.log('so many numbers!');
}Also learn how to write regular expressions, and what they actually do. Then you can also visualize them online.
Preferably 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.
Use JSDocs where applicable for JavaScript commenting.
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.
// Create the centered container.
var p = $('<p/>');
p.center(div);
p.text('foo');var container = $('<p/>');
var contents = 'foo';
container.center(parent);
container.text(contents);
megaphone.on('data', function (value) {
// The megaphone periodically emits updates for container.
container.text(value);
});// One or more digits somewhere in the string.
var numeric = /\d+/;
if (numeric.test(text)) {
console.log('so many numbers!');
}Commenting out entire blocks of code should be avoided entirely, that's why you have version control systems in place!
Variables must have meaningful names so that you don't have to resort to commenting what a piece of functionality does. Instead, try to be expressive while succinct, and use meaningful variable names.
function a (x, y, z) {
return z * y / x;
}
a(4, 2, 6);
// <- 3function ruleOfThree (had, got, have) {
return have * got / had;
}
ruleOfThree(4, 2, 6);
// <- 3Where 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.
Although we continue to support IE8, we do not support scripted interactions and rely instead on progressive enhancement to provide IE8 users with a functioning experience.
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.
Use || to define a default value. If the left-hand value is falsy then the right-hand value will be used. Be advised, that because of loose type comparison, inputs like false, 0, null or '' will be evaluated as falsy, and converted to default value. For strict type checking use if (value === void 0) { value = defaultValue }.
function a (value) {
var defaultValue = 33;
var used = value || defaultValue;
}Use .bind to partially-apply functions.
function sum (a, b) {
return a + b;
}
var addSeven = sum.bind(null, 7);
addSeven(6);
// <- 13Use Array.prototype.slice.call to cast array-like objects to true arrays.
var args = Array.prototype.slice.call(arguments);Use event emitters on all the things!
var emitter = contra.emitter();
body.addEventListener('click', function () {
emitter.emit('click', e.target);
});
emitter.on('click', function (elem) {
console.log(elem);
});
// simulate click
emitter.emit('click', document.body);Use Function() as a "no-op".
function (cb) {
setTimeout(cb || Function(), 2000);
}The original version of this document is based on Nicolas Bevacqua's functon qualityGuide, which is licensed under the MIT license.