Skip to content

Update JS Guidlines #171

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 9, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 43 additions & 60 deletions docs/coding/javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,13 @@ var string += 'Foo';
string += bar;
string += baz();
```
- :heavy_check_mark: DO configure ESLint rules `space-infix-ops` and `space-unary-ops` with option `"error"`.

## CamelCasing
Unlike the variables and functions defined in Drupal's PHP, multi-word variables and functions in JavaScript should be lowerCamelCased. The first letter of each variable or function should be lowercase, while the first letter of subsequent words should be capitalized. There should be no underscores between the words.
Multi-word variables and functions in JavaScript should be lowerCamelCased. The first letter of each variable or function should be lowercase, while the first letter of subsequent words should be capitalized. There should be no underscores between the words.
- :heavy_check_mark: DO configure ESLint rule `camelcase` with option `["error", {"properties": "always"}]`.

## Semi-colons
- :heavy_check_mark: DO use a semi-colon except where it's not allowed

JavaScript allows any expression to be used as a statement and uses semi-colons to mark the end of a statement. However, it attempts to make this optional with "semi-colon insertion", which can mask some errors and will also cause JS aggregation to fail. All statements should be followed by `;` except for the following: `for`, `function`, `if`, `switch`, `try`, `while`

Expand All @@ -78,89 +79,72 @@ do {
```
These should all be followed by a semi-colon. In addition the `return` value expression must start on the same line as the return keyword in order to avoid semi-colon insertion.

If the "Optimize JavaScript files" performance option in Drupal 6 is enabled, and there are missing semi-colons, then the JS aggregation will fail. It is therefore very important that semi-colons are used.
- :heavy_check_mark: DO use a semi-colon except where it's not allowed
- :heavy_check_mark: DO configure ESLint rule `semi` with option `["error", "always"]`. If using TypeScript, use rule `@typescript-eslint/semi` instead and turn `semi` off.

## Control Structures
These include `if`, `for`, `while`, `switch`, etc. Here is an example if statement, since it is the most complicated of them:
```js
if (condition1 || condition2)
{
if (condition1 || condition2) {
action1();
}
else if (condition3 && condition4)
{
else if (condition3 && condition4) {
action2();
}
else
{
else {
defaultAction();
}
```
Control statements should have a new line between the control keyword and opening parenthesis, to distinguish them from function calls.

Control statements should have single spaces between the control keyword, control condition, and opening parenthesis.
- :grey_question: STRONGLY CONSIDER using curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added.

### switch
For `switch` statements:
```js
switch (condition)
{
switch (condition) {
case 1:
action1();
break;
action1();
break;

case 2:
action2();
break;
action2();
break;

default:
defaultAction();
defaultAction();
}
```

### try
The try class of statements should have the following form:
```js
try
{
// Statements...
try {
// Statements...
}
catch (error)
{
// Error handling...
catch (error) {
// Error handling...
}
finally
{
// Statements...
finally {
// Statements...
}
```
Omit the `catch` or `finally` clauses if they are not needed, but never omit both.

### for in

The `for in` statement allows for looping through the names of all of the properties of an object. Unfortunately, all of the members which were inherited through the prototype chain will also be included in the loop. This has the disadvantage of serving up method functions when the interest is in data members. To prevent this, the body of every for in statement should be wrapped in an if statement that does filtering. It can select for a particular type or range of values, or it can exclude functions, or it can exclude properties from the prototype. For example:
```js
for (var variable in object) if (filter)
{
// Statements...
for (var variable in object) {
if (filter) {
// Statements...
}
}
```
- :grey_question: CONSIDER avoiding `for in` in favor of `Object.keys(obj).forEach(` which doesn't include properties in the prototype chain
- :grey_question: CONSIDER configuring ESLint rule `guard-for-in` with option `"error"`, or avoiding `for in` in favor of `Object.keys(obj).forEach(` which doesn't include properties in the prototype chain.

## Functions

### Functions and Methods

Functions and methods should be named using lowerCamelCase. Function names should begin with the name of the module or theme declaring the function, to avoid collisions. Named function expressions are generally preferable, though not very commonly used in jquery.
```js
Drupal.behaviors.tableDrag = function (context) {
for (var base in Drupal.settings.tableDrag) {
if (!$('#' + base + '.tabledrag-processed', context).size()) {
$('#' + base).filter(':not(.tabledrag-processed)').each(addBehavior);
$('#' + base).addClass('tabledrag-processed');
}
}
};
```

### Function Calls
Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example:
```js
Expand All @@ -172,6 +156,8 @@ div.onclick = function (e) {
return false;
};
```
- :heavy_check_mark: DO configure ESLint rule `func-call-spacing` with option `["error", "never"]`.
- :heavy_check_mark: DO configure ESLint rule `space-before-function-paren` with option `["error", {"anonymous": "always", "named": "never", "asyncArrow": "always"}]`.

### Function Declarations
```js
Expand All @@ -181,6 +167,7 @@ function funStuff(field) {
}
```
Arguments with default values go at the end of the argument list. Always attempt to return a meaningful value from a function if one is appropriate. Please note the special notion of anonymous functions explained above.
- :heavy_check_mark: DO configure ESLint rule `default-param-last` with option `"error"`.

## Variables and Arrays
All variables should be declared with `const` unless you need to use `let` before they are used and should only be declared once. Doing this makes the program easier to read and makes it easier to detect undeclared variables that may become implied globals.
Expand All @@ -193,7 +180,7 @@ someArray = ['hello', 'world']
```

## Comments
Inline documentation for source files should follow the [Doxygen formatting conventions](http://drupal.org/node/1354).
Inline documentation for source files should follow the [jsdoc formatting conventions](https://jsdoc.app/about-getting-started.html).
Non-documentation comments are strongly encouraged. A general rule of thumb is that if you look at a section of code and think "Wow, I don't want to try and describe that", you need to comment it before you forget how it works. Comments can be removed by JS compression utilities later, so they don't negatively impact on the file download size.

Non-documentation comments should use capitalized sentences with punctuation. All caps are used in comments only when referencing constants, e.g., TRUE. Comments should be on a separate line immediately before the code line or block they reference. For example:
Expand Down Expand Up @@ -226,6 +213,7 @@ let o = foo.bar.foobar;
o.abc = true;
o.xyz = true;
```
- :heavy_check_mark: DO configure ESLint rule `no-with` with option `"error"`.

## Operators

Expand All @@ -239,20 +227,25 @@ to be true. This can mask type errors. When comparing to any of the following va
0 '' undefined null false true
```
`!=` and `==` are good for handling `undefined | null`
- :no_entry: AVOID the `==` and `!=` operators in favor of `===` or `!==`, unless checking against the literal `null` when checking against both `null` and `undefined` is desired.
- :heavy_check_mark: DO - Configure ESLint rule `eqeqeq` with option `["error", "smart"]`.

### Comma Operator
The comma operator causes the expressions on either side of it to be executed in left-to-right order, and returns the value of the expression on the right, and should be avoided. Example usage is:
```js
var x = (y = 3, z = 9);
```
This sets x to 9. This can be confusing for users not familiar with the syntax and makes the code more difficult to read and understand. So avoid the use of the comma operator except for in the control part of for statements. This does not apply to the comma separator (used in object literals, array literals, etc.)
- :no_entry: AVOID the comma operator
- :heavy_check_mark: DO - Configure ESLint rule `no-sequences` with option `"error"`.

### Avoiding unreachable code
To prevent unreachable code, a `return`, `break`, `continue`, or `throw` statement should be followed by a } or `case` or `default`.
- :heavy_check_mark: DO - Configure ESLint rule `no-unreachable` with option `"error"`.

## Constructors
Constructors are functions that are designed to be used with the `new` prefix. The `new` prefix creates a new object based on the function's prototype, and binds that object to the function's implied this parameter. JavaScript doesn't issue compile-time warning or run-time warnings if a required `new` is omitted. If you neglect to use the `new` prefix, no new object will be made and this will be bound to the global object (bad). Constructor functions should be given names with an initial uppercase and a function with an initial uppercase name should not be called unless it has the `new` prefix.
- :heavy_check_mark: DO - constructor should also share the function name.
- :heavy_check_mark: DO use ES2015 class syntax, downleveling via Babel transpilation if obsolete browsers must be supported.

## Use literal expressions
Use literal expressions instead of the new operator:
Expand All @@ -268,12 +261,14 @@ if (literalNum) { } // false because 0 is a false value, will not be executed.
if (objectNum) { } // true because objectNum exists as an object, will be executed.
if (objectNum.valueOf()) { } // false because the value of objectNum is 0.
```
- :heavy_check_mark: DO configure ESLint rules `no-new-wrappers`, `no-new-object`, and `no-array-constructor` with option `"error"`.

## eval is evil
`eval()` is evil. It effectively requires the browser to create an entirely new scripting environment (just like creating a new web page), import all variables from the current scope, execute the script, collect the garbage, and export the variables back into the original environment. Additionally, the code cannot be cached for optimization purposes. It is probably the most powerful and most misused method in JavaScript. It also has aliases. So do not use the `Function` constructor and do not pass strings to `setTimeout()` or `setInterval()`.
`eval()` is evil. It effectively requires the browser to create an entirely new scripting environment (just like creating a new web page), import all variables from the current scope, execute the script, collect the garbage, and export the variables back into the original environment. Additionally, the code cannot be cached for optimization purposes. It is probably the most powerful and most misused method in JavaScript. It also has aliases. So do not use the `Function` constructor and do not pass strings to `setTimeout()` or `setInterval()`. NEVER pass untrusted strings to `eval()` or similar functions.
- :heavy_check_mark: DO configure ESLint rules `no-implied-eval` and `no-new-func` with option `"error"`.

## Preventing XSS
All output to the browser that has been provided by a user should be run through the `Drupal.checkPlain()` function first. This is similar to Drupal's PHP `check_plain()` and encodes special characters in a plain-text string for display as HTML.
Rendering untrusted strings to HTML should be done through the appropriate mechanisms for the framework being used, if any. For example, `{{interpolation}}` for Vue and Angular, `{interpolation}` for React, or `data-bind="text: stringVariable"` for Knockout. If no framework is being used, untrusted input should be rendered by setting the [`textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent) of the desired DOM node or by creating a new text node with [`document.createTextNode()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode).

## Typeof
When using a typeof check, don't use the parenthesis for the typeof. The following is the correct coding standard:
Expand All @@ -282,15 +277,3 @@ if (typeof myVariable == 'string') {
// ...
}
```

## Modifying the DOM
When adding new HTML elements to the DOM, don't use `document.createElement()`. For cross-browser compatibility reasons and also in an effort to reduce file size, you should use the jQuery equivalent.
- :no_entry: Dont:
```js
this.popup = document.createElement('div');
this.popup.id = 'autocomplete';
```
- :heavy_check_mark: Do:
```js
this.popup = $('<div id="autocomplete"></div>')[0];
```