NOTE: This 'research' was originally published as a blog article at https://seravo.fi/2013/javascript-the-winning-style and then transformed into a public Git repo on suggestion by Eric Elliott.
If your code is easy to read, there will be fewer bugs, any remaining bugs will be easier to debug and new coders will have a lower barrier to participate in your project. Everybody agrees that investing a bit of time to following an agreed-upon coding style is worth all the benefits it yields. Unlike Python and some other languages, JavaScript does not have an authoritative style guide. Instead there are several popular ones:
- Google JavaScript Style Guide
- npm’s coding style
- Felix’s Node.js Style Guide
- Idiomatic JavaScript
- jQuery JavaScript Style Guide
- Douglas Crockford’s JavaScript coding style
Then of course, there are also the default settings chosen in JavaScript syntax checkers JSLint and JSHint. The question is, what is the ultimate JavaScript style to rule them all? Let’s make a consensus based on these six style guides.
Two spaces, not longer and no tabs: Google, npm, Node.js, Idiomatic
Tabs: jQuery
Four spaces: Crockford
Use sparingly like below: Google, npm, Node.js
project.MyClass = function(arg1, arg2) {
Use excessive white space like below: Idiomatic, jQuery
for ( i = 0; i < length; i++ ) {
No expressed opinion: Crockford
Many guides remind not to have any trailing spaces!
Max 80 characters: Google, npm, Node.js, Crockford
When wrapping, other indentation than two spaces is allowed to for example align function arguments to the position where the first function argument was. Another option is to use four spaces instead of two when word wrapping long lines.
No expressed opinion: jQuery, Idiomatic
Always use semicolons and don’t rely on implicit insertion: Google, Node.js, Crockford
Don’t use except in some situations: npm
No expressed opinion: jQuery, Idiomatic
JSDoc conventions: Google, Idiomatic
In the Idiomatic Style Guide also simpler comments are allowed, but JSDoc encouraged.
No expressed opinion: npm, Node.js, jQuery, Crockford
Prefer '
over "
: Google, Node.js
Double quotes: jQuery
No expressed opinion: npm, Idiomatic, Crockford
One per line and no commas: Node.js
var foo = '';
var bar = '';
Multiple in one go with line ending commas like below: Idiomatic, jQuery
<