Skip to content

Commit 0263c79

Browse files
committed
Create STYLEGUIDE.md
1 parent 78c4c36 commit 0263c79

File tree

1 file changed

+382
-0
lines changed

1 file changed

+382
-0
lines changed

STYLEGUIDE.md

+382
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,382 @@
1+
# OpenUserJS.org Style Guide
2+
3+
4+
5+
### Preliminary Notes
6+
7+
Many of these conventions are influenced by **Douglas Crockford**'s *[Code Conventions for the JavaScript Programming Language][codeconventions]*.
8+
9+
The long-term value of software to an organization is in direct proportion to the quality of the codebase. Over its lifetime, a program will be handled by many pairs of hands and eyes. If a program is able to clearly communicate its structure and characteristics, it is less likely that it will break when modified in the never-too-distant future.
10+
11+
Code conventions can help in reducing the brittleness of programs.
12+
13+
All of our JavaScript code is sent directly to the public. It should always be of publication quality.
14+
15+
Neatness counts.
16+
17+
---
18+
19+
### EditorConfig
20+
21+
To help with the above rules, we use [EditorConfig][editorconfig]. Install the plugin for your text-editor or IDE.
22+
23+
---
24+
25+
### Variable Declarations
26+
27+
All variables should be declared before used. JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that may become implied globals. Implied global variables should never be used.
28+
Variable declarations without value should be initialized to `null`
29+
30+
All variable statements should be the first statements within the function body.
31+
32+
Each variable declaration should be separate, on its own line, in alphabetical order, e.g.,
33+
```javascript
34+
var baz = 'meep';
35+
var foo = true;
36+
var qux = 50;
37+
```
38+
39+
JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.
40+
41+
Use of global variables should be minimized. Implied global variables should never be used.
42+
43+
---
44+
45+
### Function Declarations
46+
47+
All functions should be declared, before they are used, after the variable declarations.
48+
49+
* There should be no space between the name of a function and the left-parenthesis of its parameter list.
50+
* There should be one space between the right-parenthesis and the left-curly-brace that begins the statement body.
51+
* The body itself is indented two spaces.
52+
* The right-curly-brace is aligned with the line containing the beginning of the function declaration.
53+
54+
```javascript
55+
function outer(c, d) {
56+
var e = c * d;
57+
58+
function inner(a, b) {
59+
return (e * a) + b;
60+
}
61+
62+
return inner(0, 1);
63+
}
64+
```
65+
66+
When a function is to be invoked immediately, the entire invocation expression should be wrapped in parenthesis so that it's clear that the value being produced is the result of the function being invoked and not the function itself.
67+
68+
```javascript
69+
var collection = (function () {
70+
// code here
71+
}());
72+
```
73+
74+
If a function literal is anonymous, there should be one space between the word `function` and the left-parenthesis.
75+
If the space is omitted, then it can appear that the function's name is `function`, which is incorrect.
76+
77+
```javascript
78+
div.onclick = function (e) {
79+
return false;
80+
};
81+
82+
that = {
83+
method: function () {
84+
return this.datum;
85+
},
86+
datum: 0
87+
};
88+
```
89+
90+
---
91+
92+
### JavaScript Files
93+
94+
JavaScript programs should be stored in and delivered as `.js` files.
95+
96+
JavaScript code should not be embedded in HTML files unless the code is specific to a single session.
97+
Code in HTML adds significantly to pageweight with no opportunity for mitigation by caching and compression.
98+
99+
`<script src="filename.js">` tags should be placed as late in the `<body>` as possible.
100+
This reduces the effects of delays imposed by script loading on other page components.
101+
There is no need to use the *language* or *type* attributes. It is the server, not the script tag, that determines the MIME type.
102+
103+
---
104+
105+
### Indentation & White Space
106+
107+
The unit of indentation is two spaces.
108+
109+
* Lines should not have trailing white space.
110+
* Files should contain exactly one newline at the end.
111+
* Blank lines improve readability by setting off sections of code that are logically related.
112+
113+
Blank spaces should be used in the following circumstances:
114+
* A keyword followed by a left-parenthesis should be separated by a space.
115+
* A blank space should not be used between a function value and its left-parenthesis. This helps to distinguish between keywords and function invocations.
116+
* All binary operators except period, left-parenthesis, and left-bracket should be separated from their operands by a space.
117+
* No space should separate a unary operator and its operand except when the operator is a word such as `typeof`
118+
* Each semi-colon in the control part of a `for` statement should be followed with a space.
119+
* Whitespace should follow every comma.
120+
121+
---
122+
123+
### Line Length
124+
125+
Avoid lines longer than 100 characters. When a statement will not fit on a single line, it may be necessary to break it.
126+
Place the break after an operator, ideally after a comma. A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion.
127+
The next line should be indented 2 spaces more than the previous line on a line-break.
128+
129+
---
130+
131+
### Comments
132+
133+
Be generous with comments. It is useful to leave information that will be read at a later time by people *(possibly yourself)* who will need to understand what you have done.
134+
The comments should be well-written and clear, just like the code they are annotating. An occasional nugget of humor might be appreciated. Frustrations and resentments will not.
135+
136+
It is important that comments be kept up-to-date. Erroneous comments can make programs even harder to read and understand.
137+
138+
Make comments meaningful. Focus on what is not immediately obvious. Don't waste the reader's time with stuff like
139+
```javascript
140+
var i = 0; // set i to zero.
141+
```
142+
143+
Instead, add comments that clarify what a line or block of code is doing, if not already obvious.
144+
145+
Generally, use line comments. Save block comments for formal documentation and for commenting out.
146+
147+
---
148+
149+
### Naming
150+
151+
Variable and function names should be clearly descriptive of what they contain, in the context of the application.
152+
153+
Names should be formed from the 26 upper and lower case letters *(A-Z, a-z)*, the 10 digits _(0-9)_, and the underscore *(_)*.
154+
Avoid use of international characters because they may not read well or be understood everywhere. Do not use the dollar sign *($)* or backslash *(\)* in names.
155+
156+
Do not use an underscore *(_)* as the first character of a name. It is sometimes used to indicate privacy, but it does not actually provide privacy.
157+
If privacy is important, use the forms that provide private members. Avoid conventions that demonstrate a lack of competence.
158+
159+
Normal variables and functions should be [camel-case][camelcase], starting with a lower-case letter.
160+
161+
Constructor functions which must be used with the new prefix should start with a capital letter.
162+
JavaScript issues neither a compile-time warning nor a run-time warning if a required `new` is omitted. Bad things can happen if `new` is not used, so the capitalization convention is the only defense we have.
163+
164+
Global variables should be in all caps. *(JavaScript does not have macros or constants, so there isn't much point in using all caps to signify features that JavaScript doesn't have.)*
165+
166+
Variables that contain regular expressions should begin with `r` and be camel-cased *(except if the phrase is an acronym like HTML)*.
167+
```javascript
168+
var rSelector = /^\*|^\.[a-z][\w\d-]*|^#[^ ]+|^[a-z]+|^\[a-z]+/i; // matches a CSS selector
169+
var rHTML = /<[^>]+>/; // matches a string of HTML
170+
```
171+
172+
---
173+
174+
### Statements
175+
176+
###### Simple Statements
177+
178+
Each line should contain, at most, one statement. Put a semi-colon at the end of every simple statement.
179+
Note that an assignment statement, which is assigning a function literal or object literal, is still an assignment statement and must end with a semicolon.
180+
181+
JavaScript allows any expression to be used as a statement. This can mask some errors, particularly in the presence of semi-colon insertion.
182+
The only expressions that should be used as statements are assignments and invocations.
183+
184+
###### Compound Statements
185+
186+
Compound statements are statements that contain lists of statements enclosed in curly braces `{ }`.
187+
188+
* The enclosed statements should be indented two more spaces.
189+
* The left-curly-brace should be at the end of the line that begins the compound statement.
190+
* The right-curly-brace should begin a line and be indented to align with the beginning of the line containing the matching left-curly-brace.
191+
* Braces should be used around all statements, even single statements, when they are part of a control structure, such as an `if` or `for` statement. This makes it easier to add statements without accidentally introducing bugs.
192+
193+
###### return Statement
194+
195+
A `return` statement with a value should not use parentheses around the value.
196+
The return value expression must start on the same line as the `return` keyword in order to avoid semi-colon insertion.
197+
198+
###### if Statement
199+
200+
The `if` class of statements should have the following form:
201+
202+
```javascript
203+
if (condition) {
204+
// statements
205+
}
206+
207+
if (condition) {
208+
// statements
209+
} else {
210+
// statements
211+
}
212+
213+
if (condition) {
214+
// statements
215+
} else if (condition) {
216+
// statements
217+
} else {
218+
// statements
219+
}
220+
```
221+
222+
###### for Statement
223+
224+
A for class of statements should have the following form:
225+
226+
```javascript
227+
for (initialization; condition; update) {
228+
// statements
229+
}
230+
231+
for (variable in object) {
232+
if (filter) {
233+
// statements
234+
}
235+
}
236+
```
237+
238+
The first form should be used with arrays and with loops of a predeterminable number of iterations.
239+
240+
The second form should be used with objects. Be aware that members that are added to the prototype of the object will be included in the enumeration.
241+
It is wise to program defensively by using the `hasOwnProperty` method to distinguish the true members of the object.
242+
243+
###### while Statement
244+
245+
A `while` statement should have the following form:
246+
247+
```javascript
248+
while (condition) {
249+
// statements
250+
}
251+
```
252+
253+
###### do Statement
254+
255+
A `do` statement should have the following form:
256+
257+
```javascript
258+
do {
259+
// statements
260+
} while (condition);
261+
```
262+
263+
Unlike the other compound statements, the `do` statement always ends with a semi-colon.
264+
265+
###### switch Statement
266+
267+
A `switch` statement should have the following form:
268+
269+
```javascript
270+
switch (expression) {
271+
case expression: {
272+
// statements
273+
break;
274+
}
275+
default: {
276+
// statements
277+
}
278+
}
279+
```
280+
281+
Each group of statements *(except the default)* should end with `break`, `return`, or `throw`. **Do not fall through.**
282+
283+
###### try Statement
284+
285+
The `try` class of statements should have the following form:
286+
287+
```javascript
288+
try {
289+
// statements
290+
} catch (variable) {
291+
// statements
292+
}
293+
294+
try {
295+
// statements
296+
} catch (variable) {
297+
// statements
298+
} finally {
299+
// statements
300+
}
301+
```
302+
303+
---
304+
305+
### Literals
306+
307+
* Use `{}` instead of `new Object()`
308+
* Use `[]` instead of `new Array()`
309+
* Use `/foo/` instead of `new RegExp('foo')` except where the latter is necessary
310+
311+
Use arrays when the member names would be sequential integers.
312+
Use objects when the member names are arbitrary strings or names.
313+
314+
---
315+
316+
### Assignment Expressions
317+
318+
Avoid doing assignments in the condition part of `if` and `while` statements.
319+
320+
is `if (a = b) {` intentional? Or was `if (a == b) {` intended?
321+
Avoid forms that are indistinguishable from common errors.
322+
323+
---
324+
325+
### Comma Operator
326+
327+
Avoid the use of the comma operator, except for very disciplined use, in the control part of `for` statements
328+
*(this does not apply to the comma separator, which is used in object literals, array literals, var statements, and parameter lists).*
329+
330+
---
331+
332+
### === and !== Operators
333+
334+
It is almost always better to use the `===` and `!==` operators.
335+
The `==` and `!=` operators do [type coercion][typecoercion] and can produce unexpected results.
336+
337+
---
338+
339+
### Confusing Pluses and Minuses
340+
341+
Be careful to not follow a `+` with `+` or `++`. This pattern can be confusing.
342+
Insert parenthesis between them to make your intention clear.
343+
344+
```javascript
345+
total = subtotal + +myInput.value;
346+
```
347+
348+
is better written as
349+
350+
```javascript
351+
total = subtotal + (+myInput.value);
352+
```
353+
354+
so that the `+ +` is not misread as `++`
355+
356+
---
357+
358+
### Restrictions
359+
360+
The following may not be used:
361+
* implied global variables *([read more][impliedglobals])*
362+
* `eval()`
363+
* `Function` constructor (it uses `eval()`)
364+
* `with()` *(it can be highly inconsistent)*
365+
366+
Do not pass strings to `setTimeout` or `setInterval`. They use `eval()`
367+
368+
`parseInt()` must be used with a radix parameter, e.g.,
369+
```javascript
370+
var i = parseInt(num, 10); // base 10 - decimal system
371+
```
372+
373+
Read more on the [awful parts of JavaScript][awfulparts].
374+
375+
376+
377+
[awfulparts]: http://oreilly.com/javascript/excerpts/javascript-good-parts/awful-parts.html
378+
[camelcase]: http://en.wikipedia.org/wiki/CamelCase
379+
[codeconventions]: http://javascript.crockford.com/code.html
380+
[editorconfig]: http://editorconfig.org/
381+
[impliedglobals]: http://www.adequatelygood.com/Finding-Improper-JavaScript-Globals.html
382+
[typecoercion]: http://webreflection.blogspot.com/2010/10/javascript-coercion-demystified.html

0 commit comments

Comments
 (0)