r/javascript • u/mrkipling • Mar 27 '15
Airbnb JavaScript Style Guide - A mostly reasonable approach to JavaScript
https://github.com/airbnb/javascript/blob/master/README.md3
u/brotherwayne Mar 27 '15
Mostly?
38
u/mrkipling Mar 27 '15
Yes - they suggest a tab indent of 2 spaces instead of the obviously-correct value of 4. Hence, mostly reasonable :)
19
u/Asmor Mar 27 '15
Also, using spaces for indentation instead of tabs.
You can have my \t when you pry it out of my cold, dead hands.
8
u/honestbleeps Reddit Enhancement Suite Mar 27 '15
I feel like you and I are on the losing end of this debate. Everyone's all spaces now. I'm always the outlier with my tabs.
7
u/Asmor Mar 27 '15
My company's all tabs (yay!), even for alignment (d'oh) and tab width is 8 (wtf)
Personally, I like tabs for indentation and spaces for alignment.
→ More replies (5)5
Mar 27 '15
Personally, I like tabs for indentation and spaces for alignment.
I personally thought this was the result of the Great Tabs/Spaces Wars. I'm astonished that this is still a thing.
6
u/munificent Mar 28 '15
You tab freaks brought it upon yourself by having tab stops default to eight spaces on some editors and websites.
→ More replies (1)→ More replies (3)3
u/eridal Mar 27 '15
TL;DR: using tabs right requires more effort
You can use tabs, but it please take care of using them in the right place: only for "tabulate", not to "align" code .. that will only work on your screen.
Let me show an example:
$(ctx).click(function() { $(this).attr(...) .css(...) ; });and now how to properly indent with tabs
$(ctx).click(function() { →$(this).attr(...) →·······.css(...) →·······; });→ More replies (1)6
u/Asmor Mar 27 '15
Agree that spaces should be used for alignment, but disagree with your interpretation. The .css call shouldn't be aligned, it should be indented. And the semi colon should be at the same level of indentation as the first line.
$(ctx).click(function() { →$(this) →→.attr(...) →→.css(...) →; });→ More replies (8)2
u/DaemonXI Mar 27 '15
Normally I like four spaces, but JavaScript is so heavily nested with callbacks that I think using two spaces actually makes the code more readable.
3
u/mrkipling Mar 27 '15
All the more reason to use four spaces, so you don't indent too heavily. Also, ES6 promises.
I do see your point though.
→ More replies (14)11
7
u/theillustratedlife Mar 27 '15 edited Mar 27 '15
Like many people, I used 4 spaces for years, but 2 spaces has definitely been winning in JS culture. It's been the standard at the last few gigs I've consulted for and is also standard on many OSS projects.
After using it for a while I like it. It's especially nice for nested ternaries:
lorem ? lorem.ipsum ? lorem.ipsum() : lorem.dolor() : nullor ternaries with nested function calls:
return routerState.has("productID") && routerState.has("variantID") ? Store.getOrFetch( { "productID": routerState.get("productID"), "variantID": routerState.get("variantID") } ) : nullIsn't it nice how those lay on the grid?
24
u/acoard Mar 27 '15
It's especially nice for nested ternaries:
Nothing is nice about nested ternaries.
→ More replies (1)→ More replies (1)4
u/tipdbmp Mar 27 '15
It's easier to debug (you can set breakpoints) when if/else-if/else statements are being used.
var result; if (!lorem) { result = null; } else if (!lorem.ipsum) { result = lorem.dolor(); } else { result = lorem.ipsum(); }But if you insist on using nested ternary operators, then in my opinion it's better to format them in a table:
var result = !lorem ? null : !lorem.ipsum ? lorem.dolor() : lorem.ipsum() ;Note that in both cases the "good" outcome goes last and it's preceded by all the "error" checking (that's generally a good advice).
2
u/nschubach Mar 27 '15
I fall in the camp that nested ternaries are bad and should be refactored to make more sense to the casual reader so setting breakpoints on indented ternaries will never be in my code.
→ More replies (2)
3
u/pimlottc Mar 27 '15
Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.
The two examples here sort of confuse me. In the first one, name is used in the if condition, so you might as well move the var declaration to the top since it's hoisted anyway, right? But in the second example, name is not used anywhere else, so you shouldn't? First off, it's sort of seems like a useless example, since there is no reason to declare the variable in the first place. And secondly, how is actually "bad" to have the variable declaration at the top of the function here?
Maybe this needs a more realistic example for the second example, but I'm not seeing the point of distinguishing between the two cases. Or am I missing something?
5
u/mrkipling Mar 27 '15
But in the second example, name is not used anywhere else, so you shouldn't?
I actually read that as it being more important to fail-fast and exit the function immediately. If you pass the fail-fast conditions then the function begins in earnest and variable definition is the next thing that happens - but there's no point in declaring them if we're just going to bail out of the function.
3
u/pimlottc Mar 27 '15
Hmm. That could be it; but it still seems to directly contradict their own advice. After all, the variable declaration is still hoisted before the if check, isn't it?
→ More replies (3)
10
u/nawitus Mar 27 '15
Mostly good stuff.
I prefer String(foo) instead of '' + foo.
I think 4 spaces are better than 2.
'collection.length > 0' is perfectly reasonable, there's no need to use shortcuts whenever possible.
I've always used "that" over "_this", but these days this is rarely needed thanks to the fat arrow syntax.
14
u/Ryckes Mar 27 '15
I think 2 spaces make it difficult to guess which block a given statement belongs to. 4 spaces is perfect for me.
3
u/ianb Mar 27 '15
new String(foo)is such craziness (all boxing is crazy in Javascript), it makes me uncomfortable to seeString(foo)2
u/shriek Mar 28 '15
haha. What about
toString()? For the most part I've used that instead of''+foo3
u/ianb Mar 28 '15
> (null).toString() TypeError: Cannot read property 'toString' of null→ More replies (1)2
u/PlNG Mar 28 '15
Doing
String(foo) instead of '' + foois casting to the String Object as opposed to working with a simple string literal, which is going to incur a performance hit.→ More replies (1)
3
u/bio595 Mar 28 '15 edited Mar 28 '15
I'm not a massive fan of marking private variables on this with leading underscores. I prefer to create a variable in the closure scope.
It prevents someone from changing it when you don't expect them to.
2
u/theycallmemorty Mar 28 '15
Me too but it really ties you're hands of you want to inherit from the class down the road.
2
Mar 28 '15
[removed] — view removed comment
→ More replies (1)2
u/bio595 Mar 28 '15
Agreed, private means private, not protected (which doesn't really make sense in js anyway)
2
u/cwmma Mar 28 '15
Using closures for that tends to have performance impact, the big benefit of underscores is that it it very clearly says to other people what is intended to be part of the public api and what is intended for the internal api. Somebody can always much about with your code latter so there isn't really any guarenteed security, so you may as well avoid slowing everything down/breaking inheritance trying to get it.
4
Mar 27 '15
hmmm... Array.join("") vs str += "some crap"
Ran some tests - string building is nearly twice faster than array.join()... Go figure.
4
3
Mar 28 '15
Yea but how often is that important?
-1
Mar 28 '15
a millisecond here, a millisecond there... and you end up with a clunky choppy app. I'm against premature optimization, but it helps to know where the bottlenecks are.
9
Mar 28 '15 edited Mar 28 '15
I work on a Web app that has 15 years of technical debt, over one hundred of devs have touched it, we've had our fair share of performance issues. Improper caching, no caching, over caching, bad 3rd party libraries, bad db queries, bad configuration, nested loops, synchronous tasks that should be async, those are the usual suspects, string concatenation has never come close to a bottle neck.
2
2
u/pimlottc Mar 27 '15
Perform type coercion at the beginning of the statement.
// => this.reviewScore = 9;
// bad
var totalScore = this.reviewScore + '';
// good
var totalScore = '' + this.reviewScore;
// bad
var totalScore = '' + this.reviewScore + ' total score';
// good
var totalScore = this.reviewScore + ' total score';By their own rule, shouldn't these be bad/good/good/bad?
3
u/theillustratedlife Mar 27 '15
How about
String(totalScore)ortotalScore.toFixed()?Say what you mean; explicit is better than implicit.
1
u/wreckedadvent Yavascript Mar 27 '15
Well, one could arguably be explicit about things like
new Object()as well, but this is not usually considered idiomatic javascript.3
u/theillustratedlife Mar 27 '15
Adding an empty string instead of calling the method that's whole purpose is to return the value cast to a string is idiomatic JavaScript?
→ More replies (1)2
u/cresquin Mar 28 '15
no, because the standalone type coercion isn't even necessary in the second 2 examples.
1
u/pimlottc Mar 28 '15
I see what you mean. They're still coercing the type, just with a string at the end of the statement, though. If they mean what you mean, they should say something like "Perform 'standlone' type coercion, when necessary, at the beginning of the statement, but omit if it's not needed".
1
2
u/BONUSBOX _=O=>_();_() Mar 27 '15
// bad
Jedi.prototype = {
fight: function fight() {
console.log('fighting');
}
};
// good
Jedi.prototype.fight = function fight() {
console.log('fighting');
};wouldn't this be an even safer and more convenient way?
Object.defineProperties(Jedi.prototype, {
fight: {
value: function () {
console.log('fighting');
},
enumerable: false
}
});that way you can safely use for...in loops without hassle, prototypes are hidden and you can extend the prototype with multiple functions at once.
downside is that it's not for IE8...
→ More replies (7)2
u/qudat Mar 27 '15
To me you'd be sacrificing readability, caused by boomeranging. I tend to prefer the style of coding that flattens code.
1
u/BONUSBOX _=O=>_();_() Mar 27 '15
Object.defineProperty(Jedi.prototype, 'fight', { value: function () { console.log('fighting'); }, enumerable: false });my best offer
1
1
1
Mar 27 '15
Apropos: I'm not objecting to the choice, but why does every major style guide for JS mandate single quoted strings unless anything else is absolutely necessary?
1
u/replugged Mar 28 '15
Single quotes are also easier to type
1
Mar 28 '15
That's one of the two reasons why I ask: They're not to me and other people on certain 109-key layouts.
0
1
u/milkeater Mar 27 '15
Gotta ask a question and maybe this is my own stupidity. it talks about array slice over looping through an array to copy it, but when I look at the jsperf, it shows the while loop outperforming array slice. am I missing something?
2
Mar 28 '15
Probably readability and code size, they probably aren't copying over tens of thousands of array items much.
1
u/cwmma Mar 28 '15
One thing missing is guidance on functional expressions vs deceleration, while they state the difference they don't do anything explicit like
// bad
var funName = function () {};
//good
function funName () {}it is very confusing when you get code that mixes the two styles.
(my interal style guide is
var funName;
if (something) {
funName = function (){};
} else {
funName = function (){/*something else*/}
}
function weDeclare(){
// all things equal do a declaration
// to avoid circular dependencies among functions
}
[].map(function nameThisToo(){});1
u/g0t4 Mar 29 '15
I've always dreaded style guides that are prescriptive and not descriptive, so I created a course that explains the tradeoffs between styles. I also give suggestions about which way I lean and why. Video turned out to be a great way to discuss and manipulate different styles.
http://weshigbee.usefedora.com/courses/on-writing-javascript-well
The intro section is free to watch and here's a playlist with a few more clips I put up on youtube: https://www.youtube.com/watch?v=oXMWIz2hPuk&list=PLTSmLfJtsBUrCsIkAjGviMqzH4877Chhe
1
u/g0t4 Mar 29 '15
IMHO why most code style guides are troublesome Should I trust this code style guide?
1
u/amenadiel Mar 31 '15
I liked the style guide. A lot. I try not to use inline if() but the rest I tend to agree on.
There are parts that do not really deal with style, they are more like specific patterns (such as string concatenation) that I tend to manage using templates rather than inlining stuff.
I've been trying to use _this instead of self, but as a long time user of underscore/lodash I keep typing _.this
1
u/jekrb Mar 27 '15
Meh. I prefer Standard's style guide. https://github.com/feross/standard
1
u/azium May 09 '15
I definitely prefer Standard, but am nervous of using it heavily seeing how favorable airbnb's / google's is. I honestly thought there would be more people chiming in about this. There's some stuff in the airbnb one that I really don't like, such as the placement of
else. On the same indentation ofifis far more readable to me.2
u/jekrb May 09 '15
I use Standard pretty extensively. I don't care what anyone else uses, standard just feels more javascripty to me.
I think it's fine to have diverse styles, and the fact that JavaScript allows this diversity is brilliant.
0
u/skitch920 Mar 27 '15 edited Mar 27 '15
// bad
var superman = {
klass: 'alien'
};Hmm, seems ok to me. clazz or klass. Not really a style rule...
I don't agree with the multivar. Everyone always complains about this one, that it's more maintenance to not multi them. Like this article. No one ever argues that it's distracting. In reality, copy pasting the word var is a waste of time.
3
u/ajacksified Mar 27 '15
The most convincing argument I've seen - and I don't really care about this rule either way - is cleaner source control diffs. Changing one line (the one you actually care about) versus two (to add / remove a comma on another line along with the one you're changing.)
2
u/skitch920 Mar 27 '15 edited Mar 27 '15
Interesting point and I have no counter-argument. But I don't totally care either, as long as you're consistent. Just to illustrate what you mean:
var a = 1, b = 2;To this:
- b = 2; + b = 2, + c = 3;3
u/sime Mar 27 '15
The advantage of single-var over mult-var is that in single-var you are free to add, delete and reorder variables independently of each other. It is always the same. In multi-var there are at least 3 cases which you need to handle when editing one of the vars. Those are cases I don't need to be thinking of.
If typing
varis too much work then you should reconsider your programming style and/or learn some basic typing. Speed of typing is rarely a bottle-neck for programmers.Not to mention the readability problem that multi-var has once the initial
varis scrolled out of view.1
u/skitch920 Mar 27 '15
Advantage over typing the word
varand a semi-colon vs swapping a semi-colon with a comma? Any linter will error bad code, so your argument of being bothered by a syntax issue is slim-to-none.Typing is not my problem. Code duplication and readability is the problem. Consider 15 different non-initialized private variables for a constructor function. Are you really going to type
var15 times?What about when you initialize all the variables at the beginning of a method. Oh look, another 4 or 5
varkeywords.If they were type signatures (int, short, double, etc.), it's totally different as each one has a lot of meaning. But writing the word
var, over and over and over, just pollutes code.2
u/danneu Mar 28 '15
Consider 15 different non-initialized private variables for a constructor function. Are you really going to type var 15 times?
Yes. It should be painful to do something so nasty.
1
Mar 27 '15
Totally agree, we use airbnb where I work but changed the rule to allow the comma last approach rather than a new var per line, imo its a lot cleaner, and pretty easy to follow as long as indentation is correct (which is also enforceable anyway)
1
u/Silverwolf90 Mar 28 '15
While debugging, won't "step over" evaluate the entire var block? Isn't that annoying?
2
u/skitch920 Mar 28 '15
What are you doing in a var block besides defining variables? You can still debug named functions if that's what you're asking.
2
u/cresquin Mar 28 '15
Why would you copy/paste var? Typing
vartakes ~200ms and is fewer keystrokes than select text -> ctrl-c -> move cursor to new position -> ctrl-v.1
u/skitch920 Mar 28 '15
I was just saying it's an overused keyword and it's practically copy/pasted everywhere. It is undoubtably the most used word in the language, and in my opinion, multi-var declarations pollute code.
And just for fun, for N
vardeclarations:// ctrl-c ctrl-v 3 + 1 + N = 4 + N // var, ctrl-c, (N) ctrl-v // If you consider ctrl-c ctrl-v as 4 keystrokes instead of 2 3 + 2 + 2N = 5 + 2N // var, ctrl-c, (N) ctrl-v // var 3N // (N) varThe first case: ctrl-c ctrl-v is faster after the 2nd
var.The second case: ctrl-c ctrl-v is faster after the 5th
var.This doesn't account for the fact that
ctrlis a shared key and the finger doesn't move, nor the fact thatcandvare neighboring characters.:)
1
u/cresquin Mar 28 '15
Right, but how often do you declare all your variables at once when writing fresh code?
It's all really minor, anyway. We should be ganging up on the people who don't use var at all.
1
u/skitch920 Mar 28 '15
Good call. Who gives a shit, as long as you're consistent. Bury anybody who unknowingly appends to global scope!
1
u/pimlottc Mar 27 '15
Hmm, seems ok to me. clazz or klass.
I think that's the point - "oh wait, did I use 'clazz' or 'klass'? Whereas if it's spelled correctly, you don't have to remember which misspelling to use.
2
u/skitch920 Mar 27 '15
Well I've always use the word
clazz. Really just by nature of coming from a Java background...
http://stackoverflow.com/a/2530174/1243162As long as you're consistent.
0
u/wreckedadvent Yavascript Mar 27 '15 edited Mar 27 '15
I like pretty much everything here, from two-spaces a tab to only function expressions assigned to vars. Also like the no multi-var statements.
Only gripes here is I prefer module patterns which enforce variable privacy over private variable Hungarian notation and I strongly prefer that or self over _this. Overall, good find.
5
u/wdpttt Mar 27 '15
I prefer
.bind(this), less bugs and little performance penalty.1
u/cresquin Mar 28 '15
IE8 has no
.bind();3
Mar 28 '15
There's a really small polyfill for it
0
u/cresquin Mar 28 '15
This guide was clearly made for the actual current state of js sans polyfills. There are a number of techniques they prefer because of old ie compatibility.
2
Mar 28 '15
Airbnb doesn't support IE8 so I don't think it's quite that clear. They seem to knowingly use modern features that IE8 doesn't support.
2
0
u/nightman Mar 27 '15
Definately agree, I use Airbnb preset with https://github.com/jscs-dev/node-jscs and it's awsome.
0
0
Mar 27 '15
[deleted]
3
u/cliath Mar 28 '15 edited Mar 28 '15
That whole block of code makes me cringe. Why is
messagespassed to the functions but notlength? Or at least derivelengthfrom the argument. Why are they using+for concatenation at the same time they are trying to optimize by using.join? Wouldn't this be a better solution if you were to follow their own style guides?function inbox(messages) { var items = ['<ul>']; for (i = 0; i < messages.length; i++) { items.push('<li>'); items.push(messages[i].message); items.push('</li>'); } items.push('</ul>'); return items.join(''); }1
u/PlNG Mar 28 '15
function inbox(messages) { messages.unshift('<ul><li>'); messages.push('</li></ul>'); return messages.join('</li><li>'); }1
u/jrpelkonen Mar 28 '15
Ping, your implementation does not function the same way as the original. It adds extra empty list items, plus it assumes an array of strings is passed, whereas the original handles an array of objects with the message as an attribute.
Cliath, I agree, this example was not the best, and they are clearly violating their own principles by not using push().
Overall, I find the document to be OK, however, I would like to see some rationale added and may be some pros and cons type of discussion.
40
u/sime Mar 27 '15
That is the first JS style guide where there isn't anything stupid in it and I actually agree with what it says. The closest thing to a disagreement is single quotes only for strings, and that is only because I tend to mix them up myself.
They even got
varright which says less about them and more about the state of "JS culture". (I would have expected onevarper line to be an obvious no brainer which didn't need to be stated.)