What is the best JavaScript code style? This may be a question that is difficult to please everyone. So let's ask a different question: which code style is the most popular?
sideeffect.kr analyzed open source code hosted on GitHub and obtained some interesting results. Let's take a look.
Trailing commas vs. leading commas
Trailing comma:
var foo = 1,
bar = 2,
baz = 3;
var obj = {
foo: 1,
bar: 2,
baz: 3
};
Leading comma:
var foo = 1
, bar = 2
, baz = 3;
var obj = {
foo: 1
, bar: 2
, baz: 3
};
Trailing comma: 92.345%; leading comma: 7.655%. (Based on 1,100,251 commits.)
Spaces and Tabs
Nowadays everyone prefers spaces. Using space indentation ensures that different developers and different editor settings see the same result.
Spaces: 81.1%; Tabs: 18.9%. (Based on 2,019,550 commits.)
Whether to add a space after function names
No space
function foo() {
return "bar";
}
With space
function foo () {
return "bar";
}
No space: 67.424%; with space: 32.576%. (Based on 1,212,488 commits.)
Whether there is a space between parameters and parentheses
No space
function fn(arg1, arg2) {
//or
if (true) {
With space
function fn( arg1, arg2 ) {
// ...
}
if ( true ) {
// ...
}
No space: 94.31%; with space: 5.69%. (Based on 1,514,971 commits.)
Whether there are spaces around colons in object literals
Space after colon
{
foo: 1,
bar: 2,
baz: 3
}
No space after colon
{
foo:1,
bar:2,
baz:3
}
Space before and after colon
{
foo : 1,
bar : 2,
baz : 3
}
Space after: 62.955%; no space: 22.891%; space before and after: 14.154%. (Based on 1,300,035 commits.)
Personally, I think no space is too cramped and makes it hard to quickly distinguish keys and values. As for spaces on both sides, you would probably need to align the colons to make it look neat. According to the statistics, most programmers are too lazy to align colons (or perhaps most programmers' IDEs or editors are not smart enough?).
Conditional statements
With space
if (true) {
//...
}
while (true) {
//...
}
switch (v) {
//...
}
No space
if(true) {
//...
}
while(true) {
//...
}
switch(v) {
//...
}
With space: 78.276%; no space: 21.724%. (Based on 1,163,316 commits.)
Single quotes, double quotes
Single quotes: 56.791%; double quotes: 43.209%. (Based on 1,705,910 commits.)
Summary
So, the most popular code style is:
- Trailing commas
- Space indentation
- No space after function name
- No space between function parameters and parentheses
- Space after colon in object literals, no space before
- Space after conditional statement keywords
What is popular is not necessarily good (for example, the flu), but from a communication perspective, writing code in a popular style can make your code look more familiar to most people.