JavaScript best practices, amalgamated from a few sources, peppered with my own preferences.
- Formatting
1.1 - Tabs
1.2 - No Trailing Whitespace
1.3 - Maximum 100 Characters
1.4 - Use Semicolons
1.5 - No leading commas
1.6 - Quotes
1.7 - Braces
1.8 - Spaces
1.9 - Case
1.10 - Spelling Counts - Comments
2.1 - Use
//
for single line comments
2.2 - Indent single line comments with their respective lines of code
2.3 - Begin all single line comments with a space
2.4 - Use/** ... */
for multiple line comments - Variables 3.1 - Declaration
- Objects 4.1 - Use the literal syntax for object creation
- Arrays
5.1 - Use the literal syntax for array creation
5.2 - Use Array push - Conditionals and Loops
6.1 - Use
===
insead of==
and!==
instead of!=
6.2 - Use shortcuts for booleans, but explicit comparisons for strings and numbers
6.3 - Use braces to create blocks - Events 7.1 - When attaching data payloads to events , pass a hash instead of a raw value
- jQuery
8.1 - Prefix jQuery object variables with a
$
8.2 - Cache jQuery lookups - Resources
- 1.1 Tabs
-
Use tab size 4 for each line indent.
-
Do not use 4 spaces.
function (name) { // do something; }
- 1.2 No Trailing Whitespace No trailing whitespace at the end of a line.
-
1.3 Maximum 100 Characters Lines should be a maximum of 100 characters long. Long lines should be broken up after operators or natural divisions. Strings that cause the line to go over 100 characters should not be written across multiple lines.
// bad const longString = 'This is a super long message that is very hard to read \ because it has been broken up onto several lines. This also makes it \ difficult to search. Keep it all on one line, please.'; // good const longString = 'This is a super long message that might cause horizontal scrolling, because it is all on one line. But, it is much more searchable and easier to work with.';
-
1.4 Use Semicolons
// bad const variableName = 'value' // good const variableName = 'value';
-
1.5 No leading commas
// bad const array = [ item1: 'first' , item2: 'second' , item3: 'third' ]; // good const array = [ item1: 'first', item2: 'second', item3: 'third' ];
-
1.6 Quotes Use single quotes. Exception: Don't escape single quotes, use double quotes.
// bad const foo = "bar"; // good const foo = 'bar'; // good const foo = "Don't feed the bar";
-
1.7 Braces Opening braces go on the same line, with one space. Closing braces go on their own line. Line up closing braces with the original corresponding line.
// bad function (name) { // do something } // very bad function (name) { if (condition) { // do something } } // good function (name) { if (condition) { // do something } }
-
1.8 Spaces Space after keyword and space before brace.
// bad function(name){ // do something } // good function (name) { if (condition) { // do something } }
-
1.9 Case Use camelCase for Variables, Functions, and Instances
// good const variable = ... const variableName = ... const function() ... const functionName() ...
Use PascalCase for Classes and Constructors
```javascript
// good
const MyClass = ...
```
-
1.10 Spelling Counts Please check your spelling. Typos hurt my brain.
// bad Smrt // good Smart
-
2.1 Use
//
for single line comments// Single line comment
-
2.2 Indent single line comments with their respective lines of code
// bad // Comment const a = 1; // bad const a = 1; // Comment // good // Comment const a = 1;
-
2.3 Begin all single line comments with a space
// bad //Comment const a = 1; // good // Comment const a = 1;
-
2.4 Use /** ... */ for multiple line comments
/** Multiple * lines * of * comments */
-
3.1 Declaration Avoid declaring global variables when unnecessary. Use const or let to declare variables. Don't use var to avoid reassigning references.
// bad var a = 1; // good const a = 1;
Use let if reassigning references.
```javascript
// bad
var count = 0;
if (true) {
count += 1;
}
// good
let count = 0;
if (true) {
count += 1;
}
Group variable types together.
// bad
const a = 1;
let count = 0;
const b = 2;
// good
const a = 1;
const b = 2;
let count = 0;
```
Declare variables on a new line.
```javascript
// bad
const a = 1, b = 2;
// good
const a = 1;
const b = 2;
```
-
4.1 Use the literal syntax for object creation.
// bad const item = new Object(); // good const item = {};
-
5.1 Use the literal syntax for array creation.
// bad const items = new Array(); // good const items = [];
-
5.2 Use Array push instead of direct assignment to add items to an array.
const someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
- 6.1 Use
===
insead of==
and!==
instead of!=
-
6.2 Use shortcuts for booleans, but explicit comparisons for strings and numbers.
// bad if (isValid === true) { // ... } // good if (isValid) { // ... } // bad if (name) { // ... } // good if (name !== '') { // ... } // bad if (collection.length) { // ... } // good if (collection.length > 0) { // ... }
-
6.3 Use braces to create blocks in
case
anddefault
clauses that contain lexical declarations (e.g.let
,const
,function
, andclass
).// bad switch (foo) { case 1: let x = 1; break; case 2: const y = 2; break; case 3: function f() { // ... } break; default: class C {} } // good switch (foo) { case 1: { let x = 1; break; } case 2: { const y = 2; break; } case 3: { function f() { // ... } break; } case 4: bar(); break; default: { class C {} } }
-
7.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event.
// bad $(this).trigger('listingUpdated', listing.id); // ... $(this).on('listingUpdated', (e, listingId) => { // do something with listingId });
prefer:
```javascript
// good
$(this).trigger('listingUpdated', { listingId: listing.id });
// ...
$(this).on('listingUpdated', (e, data) => {
// do something with data.listingId
});
```
-
8.1 Prefix jQuery object variables with a
$
.// bad const sidebar = $('.sidebar'); // good const $sidebar = $('.sidebar'); // good const $sidebarBtn = $('.sidebar-btn');
-
8.2 Cache jQuery lookups.
// bad function setSidebar() { $('.sidebar').hide(); // ... $('.sidebar').css({ 'background-color': 'pink', }); } // good function setSidebar() { const $sidebar = $('.sidebar'); $sidebar.hide(); // ... $sidebar.css({ 'background-color': 'pink', }); }
-
9.1 Style Guides
-
9.2 JSHint