Carefully selected conventions based on years of experience as well as purely aesthetic preferences
Note: this guide assumes you are using Babel
-
1.1 Semicolon: JavaScript semicolons are optional. As company preference, we omit semicolons
const foo = 1 console.log(foo) // => 1
- 1.2 Traling Comma: JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ECMAScript 5) and most recently (ECMAScript 2017) to function parameters.
Why? Trailing commas can be useful when adding new elements. If you want to add a new property, you can simply add a new line without modifying the previously last line if that line already uses a trailing comma. This makes version-control diffs cleaner and editing code might be less troublesome.
```javascript
const foo = [1, 2, 3,]
const bar = {
foo: "bar",
baz: "qwerty",
age: 42,
}
```
-
2.1 Use
const
for all of your references avoid usingvar
.Why? This ensures that you can’t reassign your references, which can lead to bugs and difficult to comprehend code.
// bad var a = 1 var b = 2 // good const a = 1 const b = 2
-
2.2 If you must reassign references, use
let
instead ofvar
Why?
let
is block-scoped rather than function-scoped likevar
.// bad var count = 1 if (true) { count += 1 } // good, use the let. let count = 1 if (true) { count += 1 }
-
2.3 Note that both
let
andconst
are block-scoped.// const and let only exist in the blocks they are defined in. { let a = 1 const b = 1 } console.log(a) // ReferenceError console.log(b) // ReferenceError
-
3.3 Use object method shorthand.
// bad const atom = { value: 1, addValue: function (value) { return atom.value + value }, } // good const atom = { value: 1, addValue(value) { return atom.value + value }, }
-
3.4 Use property value shorthand.
Why? It is shorter and descriptive.
const miyamotoMusashi = 'Miyamoto Musashi' // bad const obj = { miyamotoMusashi: miyamotoMusashi, } // good const obj = { miyamotoMusashi, }
-
3.5 Group your shorthand properties at the beginning of your object declaration.
Why? It’s easier to tell which properties are using the shorthand.
const miyamotoMusashi = 'Miyamoto Musashi' const honjoMasamune = 'Honjo Masamune' // bad const obj = { katana: 1, samurai: 2, miyamotoMusashi, dojo: 3, bushi: 4, anakinSkywalker, } // good const obj = { miyamotoMusashi, anakinSkywalker, katana: 1, samurai: 2, dojo: 3, bushi: 4, }
Other Style Guides