3 JS Style Guide
Big Bad Waffle edited this page 4 years ago

Modules

  • Server-side modules are CommonJS
  • Client-side modules are AMD

Tabs or Spaces

Tabs

Whitespace

Whitespace is added in the following locations.

//After keywords
if (

//Before Brackets
if (a) {

//Around mathematical operators
var a = b + c;

//Around boolean operators
if ((a) || (b))

Bracket Positioning

if (a) {

} else {
	
}

Single or Double Quotes

Single.

var a = 'This is a string';

In cases where a single quote is required in the string, use backticks:

var a = `This string contains 'single quotes'`;

String Concatenation

To build a string up from variables, use template literals:

var a = `Name: ${name}`;

Conditionals

Each conditional has brackets surrounding it:

if ((a) && (b == c))

In cases where there are more than one operator, new-lines and indentation is used to improve readability:

if (
	(a) &&
	(
		(b == c) ||
		(b == d)
	)
)

When an if contains only one statement, no brackets are added:

if (a)
	b();

For Loops

The following iterators (in this order) are used: i, j, k, l.

Iterators are never pre-declared.

If the array terminator is a variable, it must be cached if it consists of more than one term:

//no
for (var i = 0; i < objects.length; i++)

//yes
var oLen = objects.length;
for (var i = 0; i < oLen; i++)

No other statements may be part of the loop declaration. That is, none of this:

for (var i = 0; i++, j += 1; i < 10)

In-line Functions

To manipulate/find items in arrays, arrow functions are used:

var exists = array.find(a => (a == b));

In cases where the match is calculated in more than one statement, regular functions are used:

var exists = array.find(function(a) {
	var b = a * 2;
	return (b == 4);
});

When the in-line function is a callback that is meant to be called later, bound functions are used:

db.query(queryString, this.onQuery.bind(this);

Multi-Line Strings

To build multi-line strings, use backticks and the proper indentation:

var a = `
	This is
	a multi-line
	string.
`;

JSON Objects

JSON Objects are never declared on one line:

//wrong
var a = { b: 1, c: 2 };

//right
var a = {
	b: 1,
	c: 2
};

Arrays

Small arrays can be defined on one line if spaces are placed after and before the first and last square bracket:

var a = [ 1, 2, 3 ];

Bigger arrays must be defined on multiple lines:

var a = [
	1,
	2,
	3,
	4,
	5
];

Comments

Single line comments are written with no space after the slashes:

//Single line comment

Multi-line comments are written with spaces after the brackets on all but the first line.

//Multi-line
// comment
//Another multi-line
// comment

Module Syntax

Things to note:

  • Each included module it listen on its own line.
  • Gap after properties
  • Gap after each method
  • Space after function()
define([
	'a/a',
	'a/b'
], function(
	a,
	b
) {
	return {
		propA: 1,

		methodA: function() {

		},

		methodB: function() {
		
		}
	};
});