You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* Update JS Guidlines
- Add ESLint rule recommendations
- Remove all the references to Drupal
- Remove things that are obsolete in 2021.
* Update javascript.md
* Update docs/coding/javascript.md
Co-authored-by: Steve Byerly <1393464+SteveByerly@users.noreply.github.com>
* Update javascript.md
Co-authored-by: Steve Byerly <1393464+SteveByerly@users.noreply.github.com>
Copy file name to clipboardExpand all lines: docs/coding/javascript.md
+43-60Lines changed: 43 additions & 60 deletions
Original file line number
Diff line number
Diff line change
@@ -55,12 +55,13 @@ var string += 'Foo';
55
55
string += bar;
56
56
string +=baz();
57
57
```
58
+
-:heavy_check_mark: DO configure ESLint rules `space-infix-ops` and `space-unary-ops` with option `"error"`.
58
59
59
60
## CamelCasing
60
-
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.
61
+
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.
62
+
-:heavy_check_mark: DO configure ESLint rule `camelcase` with option `["error", {"properties": "always"}]`.
61
63
62
64
## Semi-colons
63
-
-:heavy_check_mark: DO use a semi-colon except where it's not allowed
64
65
65
66
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`
66
67
@@ -78,89 +79,72 @@ do {
78
79
```
79
80
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.
80
81
81
-
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.
82
+
-:heavy_check_mark: DO use a semi-colon except where it's not allowed
83
+
-: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.
82
84
83
85
## Control Structures
84
86
These include `if`, `for`, `while`, `switch`, etc. Here is an example if statement, since it is the most complicated of them:
85
87
```js
86
-
if (condition1 || condition2)
87
-
{
88
+
if (condition1 || condition2) {
88
89
action1();
89
90
}
90
-
elseif (condition3 && condition4)
91
-
{
91
+
elseif (condition3 && condition4) {
92
92
action2();
93
93
}
94
-
else
95
-
{
94
+
else {
96
95
defaultAction();
97
96
}
98
97
```
99
-
Control statements should have a new line between the control keyword and opening parenthesis, to distinguish them from function calls.
98
+
99
+
Control statements should have single spaces between the control keyword, control condition, and opening parenthesis.
100
100
-: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.
101
101
102
102
### switch
103
103
For `switch` statements:
104
104
```js
105
-
switch (condition)
106
-
{
105
+
switch (condition) {
107
106
case1:
108
-
action1();
109
-
break;
107
+
action1();
108
+
break;
110
109
111
110
case2:
112
-
action2();
113
-
break;
111
+
action2();
112
+
break;
114
113
115
114
default:
116
-
defaultAction();
115
+
defaultAction();
117
116
}
118
117
```
119
118
120
119
### try
121
120
The try class of statements should have the following form:
122
121
```js
123
-
try
124
-
{
125
-
// Statements...
122
+
try {
123
+
// Statements...
126
124
}
127
-
catch (error)
128
-
{
129
-
// Error handling...
125
+
catch (error) {
126
+
// Error handling...
130
127
}
131
-
finally
132
-
{
133
-
// Statements...
128
+
finally {
129
+
// Statements...
134
130
}
135
131
```
132
+
Omit the `catch` or `finally` clauses if they are not needed, but never omit both.
136
133
137
134
### for in
138
135
139
136
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:
140
137
```js
141
-
for (var variable in object) if (filter)
142
-
{
143
-
// Statements...
138
+
for (var variable in object) {
139
+
if (filter) {
140
+
// Statements...
141
+
}
144
142
}
145
143
```
146
-
-:grey_question: CONSIDER avoiding `for in` in favor of `Object.keys(obj).forEach(` which doesn't include properties in the prototype chain
144
+
-: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.
147
145
148
146
## Functions
149
147
150
-
### Functions and Methods
151
-
152
-
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.
153
-
```js
154
-
Drupal.behaviors.tableDrag=function (context) {
155
-
for (var base inDrupal.settings.tableDrag) {
156
-
if (!$('#'+ base +'.tabledrag-processed', context).size()) {
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:
166
150
```js
@@ -172,6 +156,8 @@ div.onclick = function (e) {
172
156
returnfalse;
173
157
};
174
158
```
159
+
-:heavy_check_mark: DO configure ESLint rule `func-call-spacing` with option `["error", "never"]`.
160
+
-:heavy_check_mark: DO configure ESLint rule `space-before-function-paren` with option `["error", {"anonymous": "always", "named": "never", "asyncArrow": "always"}]`.
175
161
176
162
### Function Declarations
177
163
```js
@@ -181,6 +167,7 @@ function funStuff(field) {
181
167
}
182
168
```
183
169
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.
170
+
-:heavy_check_mark: DO configure ESLint rule `default-param-last` with option `"error"`.
184
171
185
172
## Variables and Arrays
186
173
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.
Inline documentation for source files should follow the [Doxygen formatting conventions](http://drupal.org/node/1354).
183
+
Inline documentation for source files should follow the [jsdoc formatting conventions](https://jsdoc.app/about-getting-started.html).
197
184
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.
198
185
199
186
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:
@@ -226,6 +213,7 @@ let o = foo.bar.foobar;
226
213
o.abc=true;
227
214
o.xyz=true;
228
215
```
216
+
-:heavy_check_mark: DO configure ESLint rule `no-with` with option `"error"`.
229
217
230
218
## Operators
231
219
@@ -239,20 +227,25 @@ to be true. This can mask type errors. When comparing to any of the following va
239
227
0''undefinednullfalsetrue
240
228
```
241
229
`!=` and `==` are good for handling `undefined | null`
230
+
-: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.
231
+
-:heavy_check_mark: DO - Configure ESLint rule `eqeqeq` with option `["error", "smart"]`.
242
232
243
233
### Comma Operator
244
234
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:
245
235
```js
246
236
var x = (y =3, z =9);
247
237
```
248
238
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.)
239
+
-:no_entry: AVOID the comma operator
240
+
-:heavy_check_mark: DO - Configure ESLint rule `no-sequences` with option `"error"`.
249
241
250
242
### Avoiding unreachable code
251
243
To prevent unreachable code, a `return`, `break`, `continue`, or `throw` statement should be followed by a } or `case` or `default`.
244
+
-:heavy_check_mark: DO - Configure ESLint rule `no-unreachable` with option `"error"`.
252
245
253
246
## Constructors
254
247
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.
255
-
-:heavy_check_mark: DO - constructor should also share the function name.
248
+
-:heavy_check_mark: DO use ES2015 class syntax, downleveling via Babel transpilation if obsolete browsers must be supported.
256
249
257
250
## Use literal expressions
258
251
Use literal expressions instead of the new operator:
@@ -268,12 +261,14 @@ if (literalNum) { } // false because 0 is a false value, will not be executed.
268
261
if (objectNum) { } // true because objectNum exists as an object, will be executed.
269
262
if (objectNum.valueOf()) { } // false because the value of objectNum is 0.
270
263
```
264
+
-:heavy_check_mark: DO configure ESLint rules `no-new-wrappers`, `no-new-object`, and `no-array-constructor` with option `"error"`.
271
265
272
266
## eval is evil
273
-
`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()`.
267
+
`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.
268
+
-:heavy_check_mark: DO configure ESLint rules `no-implied-eval` and `no-new-func` with option `"error"`.
274
269
275
270
## Preventing XSS
276
-
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.
271
+
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).
277
272
278
273
## Typeof
279
274
When using a typeof check, don't use the parenthesis for the typeof. The following is the correct coding standard:
@@ -282,15 +277,3 @@ if (typeof myVariable == 'string') {
282
277
// ...
283
278
}
284
279
```
285
-
286
-
## Modifying the DOM
287
-
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.
0 commit comments