Today I learned… that Airbnb has a fantastic JavaScript “style guide” available for free on github. The guide is light on long-winded explanations and big on DO and DON’T examples. Check it out, it’s a 15 min read at most.
Here are just a few of the things I learned from it:
Declaring multiple variables
A long list of variable declarations should be done with the unassigned variables last, and all declarations can share one use of var.
// multiple var declarations like so: var items = getItems(), daytime = true, length, i;
I’m definitely guilty of var var var var var… but I’m not sure how I feel about this particular style. I like the clarity and editability of beginning each line with var, but for declaring lots of like items, I can see the usefulness of this style.
Shortcuts for the win
Instead of writing “if this thing is greater than zero”, you can just write “if this thing”.
Here’s an example:
// bad if (cars.length > 0) { // ... code here } // good if (cars.length) { // ... code here }
Easy enough.
Comment with good style
Oops, I’ve definitely been getting this one wrong. Comments belong on their own line, not off to the right of the line the comment explains.
// bad var active = true; // is current tab // good // is current tab var active = true;
Guilty. I’ll quit doing this, as tempting as it is for the sake of shorter files…
Saving a reference to “this”
Oops, here’s another mea culpa. I’ve been saving reference to “this” as “self”, but the style guide suggests _this as a better alternative.
I’m inclined to agree – I found “self” confusing the first time I encountered it, and its relation to “this” wasn’t immediately apparent.
// bad function() { var self = this; return function() { console.log(self); }; } // bad function() { var that = this; return function() { console.log(that); }; } // good function() { var _this = this; return function() { console.log(_this); }; }
Those are just a handful of the discoveries I made while exploring this guide.
Be sure to check it out yourself and see what you could be doing better, and don’t miss the giant list of resources at the bottom of the page!