Deleting the wiki page 'JS Style Guide' cannot be undone. Continue?
Tabs
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))
if (a) {
} else {
}
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'`;
To build a string up from variables, use template literals:
var a = `Name: ${name}`;
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();
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)
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);
To build multi-line strings, use backticks and the proper indentation:
var a = `
This is
a multi-line
string.
`;
JSON Objects are never declared on one line:
//wrong
var a = { b: 1, c: 2 };
//right
var a = {
b: 1,
c: 2
};
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
];
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
Things to note:
function()
define([
'a/a',
'a/b'
], function(
a,
b
) {
return {
propA: 1,
methodA: function() {
},
methodB: function() {
}
};
});
Deleting the wiki page 'JS Style Guide' cannot be undone. Continue?