Most of the style guide recommendations here come from Douglas Crockford's book JavaScript, the good parts
We always indent 4 spaces.
We use camelCase for function names and underscores for variables names.
For example:
function thisIsAFunction () {
let this_is_a_variable;
...
}
Try to use const whenever possible. If a variable won't be reassigned, use const, otherwise use let.
In general, spaces are put around operators, such as the equals =
or plus +
signs.
For example:
if (sublocale != locale) {
// do something
}
An exception is when they appear inside for-loop expressions, for example:
for (i=0; i<msgs_length; i++) {
// do something
}
Generally though, rather err on the side of adding spaces, since they make the code much more readable.
When assigning to a variable via destructuring, add spaces between the curly brackets.
For example:
const { foo } = bar;
Global identifiers that denote constant values should be written in all capital letters, with underscores between words.
For example:
const SECONDS_IN_HOUR = 3600;
function update () {
const timeout = 20;
let seconds_since_message = 0;
// other stuff here
}
When declaring a function, the function name and the brackets after it are separated with a space. Like so:
function update (model) {
model.foo = 'bar';
}
When calling the same function, the brackets are written without a space in between:
update(model);
This is to make a more explicit visual distinction between method declarations and method invocations.
JavaScript has a strict ===
and less strict ==
equality operator. The
stricter equality operator also does type checking. To avoid subtle bugs when
doing comparisons, always use the strict equality check.
Curly brackets must appear on the same lines as the if
and else
keywords.
The closing curly bracket appears on its own line.
For example:
if (locales[locale]) {
return locales[locale];
} else {
sublocale = locale.split("-")[0];
if (sublocale != locale && locales[sublocale]) {
return locales[sublocale];
}
}
When writing a block such as an if
or while
statement, always use
curly brackets around that block of code. Even when not strictly required by
the compiler (for example if its only one line inside the if
statement).
For example, like this:
if (condition === true) {
this.updateRoomsList();
}
somethingElse();
and NOT like this:
if (converse.auto_list_rooms)
this.updateRoomsList();
somethingElse();
This is to aid in readability and to avoid subtle bugs where certain lines are wrongly assumed to be executed within a block.