9 ms·
Airbnb JavaScript Style Guide
- deleted 11y ago[deleted]
- cnp 11y agoThis is the ES6 guide I send around to those who are trying to get up to speed with JavaScript -- its fantastic.
- thomasfoster96 11y agoHaving seen this updated version I'm not terribly impressed at their guide for ES6. No mention of symbols (which are pretty important if you're using classes), generators are ignored almost entirely, a pretty poor explanation of modules, etc.
- uptown 11y agoYou're in luck! They published this in GitHub so you can suggest changes you think might make things better.
- dikaiosune 11y agoThis has always been one characteristic of open source standpoints that I'm not such a big fan of. It's too tightly coupled to expect everyone with constructive criticism to also contribute. Yes, it would be good if they did. But it would strike a serious blow to many projects' mental capital if the only feedback they took from users was from those users capable (either technically or in possession of enough free time) of contributing the changes themselves.
- thomasfoster96 11y agoWell, style guides are fairly subjective projects compared to most other open source projects, so while it might be worth my while suggesting things, it's not likely airbnb is going to change their style guide because I think differently to them. Edit: Looking at some issues in the style guide repo, AirBnB seems reluctant to add or change the style guide to deviate from what they do internally (for instance, generators are rarely used, therefore they aren't encouraged).
- anustart666 11y agoDid you even read it? They don't use the meme 'symbols' but clearly mention 'dynamic property names'. https://github.com/airbnb/javascript#3.4 https://github.com/airbnb/javascript#3.4
- thomasfoster96 11y agoDynamic property names are quite different to Symbols in ECMAScript 6.
- anustart666 11y agoUse a global const for keygen, 'symbol' is most likely just a syntactic sugar for global const...
- thomasfoster96 11y agoWell a Symbol is guaranteed to be unique (unless you use the symbol registry) and can't be converted to a string - things that you can't say about a global const that is a string.
- Ronsenshi 11y agoUm: > Don't use generators for now. >> Why? They don't transpile well to ES5. Same thing with Symbols?
- orthoganol 11y agoWhy are they worried about working by reference on numbers? // bad var a = 1; var b = 2; // good const a = 1; const b = 2;
- shredprez 11y agoAssuming I'm not misunderstanding your question, it appears to cover that right above the snippet: "Why? This ensures that you can't reassign your references (mutation), which can lead to bugs and difficult to comprehend code." So it's not about working by reference but avoiding inadvertent reassignment and resulting unpredictability.
- orthoganol 11y ago> Assuming I'm not misunderstanding your question Numbers are not passed by reference. It's a lazy example, that has the potential to confuse. I would agree with the downvoters I'm being petty, but c'mon... it's the very first thing you read in your JavaScript guide & it's flawed.
- beaner 11y agoYou're right.
- epidemian 11y agoIn JS `const` just means that you can't reassign that variable, not that the value it references can't change: const a = {foo: 5}; a.foo = 42; // This is perfectly valid. a = 'nope'; // But this isn't. It raises a SyntaxError.
- orthoganol 11y agoThe purpose of the code wasn't to illustrate how to use const. It was to show how they want you to always use const with complex types.
- anselmoars 11y ago
- ewalk153 11y agoThere is also a link on the page to browser compat style guide of es5 https://github.com/airbnb/javascript/tree/master/es5 https://github.com/airbnb/javascript/tree/master/es5
- keithwhor 11y agoLove this guide. Adhere to it as tightly as possible for most new projects, saves a lot of mental overhead. Use the ES5 version for team frontend projects. :)
- shredprez 11y agoAmen! Though I am partial to idiomatic.js' whitespace suggestions: https://github.com/rwaldron/idiomatic.js#spacing https://github.com/rwaldron/idiomatic.js#spacing Much easier to skim/parse quickly, at least for me.
- nixy 11y agoNo, no, no, this has to go away. The insertion of spaces before ) and after ( is something I see from time to time in JS code, and it is really difficult for me to read. Three.js unfortunately uses this, and mrdoob even has his own style guide. His style guide is probably the only thing I don't like about his work. No school I've studied or worked at teaches this style, and JS traditionally has never been written like this[1][2]. And now I see it elsewhere as well. In some Java projects, for example. Where does this come from? There are currently no known hard facts (conclusions from studies) about which of the whitespace styles have the best readability. So let's just all stick to the most common way of doing things, shall we :) [1] JavaScript The Good Parts [2] Google JS Style Guide http://google.github.io/styleguide/javascriptguide.xml
- chanux 11y agoI agree. 'Cramped' there is more 'readable' to me. This is probably a matter of personal preference.
- Roboprog 11y agoAh, C layout orthodoxy at its finest: shove as much crap separated only by operators without whitespace on one line as you can. (not exactly what you said, but I'm extrapolating uncharitably) I guess you could lampoon me as COBOL orthdoxy, liking spaces between symbols, but Lisp was good at using whitespace, rather than commas, between symbols as well.
- svieira 11y agoThe fact that `typeof` is no longer safe [1][2] is news to me - it feels like they put in air bags and removed the seat belts. [1]: https://github.com/airbnb/javascript#14.1 [2]: http://es-discourse.com/t/why-typeof-is-no-longer-safe/15
- wwweston 11y agoThat's... interesting. I guess it makes a little sense -- `let` seems to be for developers who don't like `var` semantics. Usually that seems to be about wanting block instead of function scope, but maybe there's a contingent that dislikes `undefined` too.
- masklinn 11y ago`let` doesn't disappear `undefined` though. >> let a; >> a; undefined
- AgentME 11y agoThe only code affected by this would be code that uses typeof to check for the existence of a variable the same code defines later, which sounds like dumb code to begin with. I don't think there's any valid uses of typeof on possibly undefined variables besides checking for browser built-ins.
- mAritz 11y agoUsing typeof(foo) === "undefined" is actually something that comes from back when it was pretty common to pollute the global namespace. There were actual javascript plugins/libraries/snippets that defined undefined and thus broke code that compared to it.
- ahoge 11y agoIt's not an issue since using a non-hoisted variable before it was declared is an error. Your editor should immediately highlight this error with a squiggly line.
- seniorsassycat 11y agoI'd like to see the justifications for some of these, particularly 3.5 which I see as only obscuring that the current context is a function.
- arxpoetica 11y agoAgreed. That's pretty obscure.
- savanaly 11y agoMajor advantage: fewer characters to type and parse (parse with your eyes, that is). Major disadvantage: in the short term it might be difficult to parse. Possible additional major disadvantage: programmers may never adapt and find it difficult to parse for ever more.
- atinoda-kestrel 11y agoYeah, I'm not sold on "fewer characters" as a win. 'cause then we can have the code golf arguments that inevitably get into the nutty realm. For visual parsing, consistency matters. In an object literal dec I expect: name : value That's easy to parse visually. Not good is when suddenly we get: nameandvalue(){ in the space that our brain expects the former.
- vivianLTP 11y agoI'm a big fan of javascript.
- tehwebguy 11y agoI didn't know you could do this! // good const obj = { id: 5, name: 'San Francisco', [getKey('enabled')]: true, };
- natrius 11y agoNext to arrow functions and optional arguments, better object syntax is one of the big reasons you should be using Babel today. You know how sometimes you need to precalculate values that are going to be returned in an object, so at the end of the function, you return something like this? return { foo: foo, bar: bar, baz: baz }; You don't have to do that in ES6. return {foo, bar, baz}; Keys without values use variables with the same name as their values.
- taternuts 11y agoYep, computed property names is another ES6 feature
- BurningFrog 11y agoMaybe this is the IPA talking, but I don't think I ever want to work at a company with a style guide again. This is no worse that others I've seen, but they all codify what some group found useful at some point in time, and then that becomes Company Policy set in stone for the rest of time.
- tehwebguy 11y agoAt 472 commits my guess is it's truly a "guide" rather than a rulebook and a living, changing one at that!
- BurningFrog 11y agoGive it time...
- debaserab2 11y agoIt looks like airbnb does a good job updating theirs, but I can sympathize with the parent comment. I've found coding style guides that end up obtuse, easily outdated, and arbitrarily fit to the preferences of it's creators. They often stagnate and are blindly followed just for the sake of following. A lot of the best practices in the document are things that should be screened for at the hiring stage, and many of the others are heavily debatable preferences that are only going to make a developer with an opposing opinion feel needlessly boxed. Not that they are a bad thing and airbnb's looks really solid to me, but writing a coding style guide means you now need to maintain and curate it periodically – a process that is easy to neglect.
- forrestthewoods 11y agoThe alternative is that every coder has their own style and over time every file becomes random and wildly inconsistent. That doesn't sound good to me either.
- BurningFrog 11y agoIt makes sense to me that each team decides their coding standard. 5 or 20 engineers who work in the same code base should have some more or less formal standards for that code.
- nodesocket 11y agoVery nice work, but not sure that I'm onboard with switching `var` to `const | let`. Is the only difference between `var` and `let` scoping?
- iMark 11y agoNot just scoping. The hoisting rules have changed. There's some discussion earlier in the comments regarding `typeof` no longer being safe to use with `let` and `const` declarations. `typeof` with a `var` before its declaration is fine because of hoisting, but with `let` produces a reference error.
- Roboprog 11y agoI didn't even know there were "hoisting" rules - I put all my variables on one var line at the top of the file, then assign them later. Well, except for lately, function variables in JSDoc work better when the function-var is immediately assigned :-(
- brwnll 11y agoThe best part of this guide is that they included a eslint and jslint rules file. https://github.com/airbnb/javascript/tree/master/linters https://github.com/airbnb/javascript/tree/master/linters My team adopted this style guide and was easily able to add it as a eslint step to our existing gulp files and run it automatically. This let us use the guide without making everyone memorize the syntax differences between their personal style first.
- manojlds 11y agoES5 guide - https://github.com/airbnb/javascript/blob/master/es5 https://github.com/airbnb/javascript/blob/master/es5
- BinaryIdiot 11y agoLooks like a lot of good stuff but it's incredibly verbose and dense. It's important to adhere to standards but I'm not entirely convinced this doesn't end up being counter-productive. But as long as it's a guide and not a 100% "you must follow every little thing" and you can change things then maybe it's not so bad. Still hard to get used to so many using ES6 already. I'm still not a big fan of transpiling but some days I feel like I'm the only one.
- Todd 11y agoYes, there is a mix of pragmatic advice (with citations) along with stylistic opinions. I think the ES5 version is also quite good. Look at the number of forks, though. I might use this as the basis for a style guide for my organization. I think I'll probably fork it, though, and remove the opinionated bits. I did enjoy the writing style.
- wnevets 11y ago2.2 seems completely arbitrary to me. If your functions are so big that you need block scope, you're doing it wrong IMO.
- joeblow99 11y ago// bad const item = new Object(); // good const item = {}; Literally useless differentiation.
- razwall 11y agoSeems pretty useful to me. If I see "new Object()", I know the code was written by someone who doesn't know JS very well, so I should look more carefully for bugs.
- roelvanhintum 11y agoSame functionality, less characters. This also helps being consistent.
- Ronsenshi 11y agoThat's why they call it Style Guide. You know - Style?
- jeffpeterson 11y agoHah, "literally"
- joeblow99 11y ago// bad const items = new Array(); // good const items = []; They obviously spent a lot of time on this guide, lots of investor dollars, and it's of almost no use.
- roelvanhintum 11y agoMaking sure everyone within your company writes the same style code, makes it more readable and easier to find bugs. You can also start doing automatic linting and hinting. On top of that, they made the top on hacker news which will help finding new devs.
- odabaxok 11y agoImagine this: a = new Array(10); b = [10]; alert(a[0]); alert(b[0]); Do you know the difference? This is just one reason. Also [] will be faster. Just google the differences and why [] is recommended to use.
- ahoge 11y ago> new Array('a') ["a"] > new Array(2, 3) [2, 3] > new Array(2) [undefined, undefined] > new Array(2.3) RangeError: invalid array length > new Array(2.3, 4.5) [2.3, 4.5] The Array constructor is really bogus. It switches to a different mode if a single number is passed. ES6 added `Array.of` for this reason: > Array.of() [] > Array.of(1) [1] > Array.of(1, 2) [1, 2] I don't really think it's needed though. Spread and rest already take care of the common use cases.
- elisee 11y agoRegarding using single quotes for strings (https://github.com/airbnb/javascript#6.1 https://github.com/airbnb/javascript#6.1), I found it interesting that it's one of the rare sections where there's no rationale offered. I guess it's just a stylistic choice in the end, but when we set up our own internal/informal style guide, my teammate and I spent a little while trying to come up with a justification for single vs double quotes. We ended up choosing double quotes based on the fact that JSON already made that decision for us: it requires strings be double-quoted. (Although again, it's far from an important matter, as long as you're consistent), anybody has interesting rationales to share in favor of single quotes?
- _jnc 11y agoAt least in Ruby, you can only do string interpolation with strings in double quotes.
- elisee 11y agoJavaScript up to ES5 doesn't support string interpolation at all. ES6 introduces backticks `before${var}after` for that, but there's still no functional difference between single and double quotes.
- mixmastamyk 11y agoInteresting they chose that, considering it's deprecated in bash and python.
- sprobertson 11y agoCoffeescript as well. I try to use single quotes whenever possible, so if a string is templated it stands out a bit with the double quotes.
- NhanH 11y agoIf JSON requires the string to be double-quoted, then it's more convenient to use singe quotes, since your embedded JSON string (if you ever used it) won't need to have its quotes escaped.
- joeblow99 11y agoUse const for all of your references; avoid using var. If you must mutate references, use let instead of var. In my 15 years of programming javascript I've never once seen this matter.
- RoboSeldon 11y agoThat's because let and const where officially introduced in JavaScript this year, see the JavaScript standard ES6 (or ES2015).
- wes-exp 11y agoAirbnb's technical quality has been obviously crap for its entire existence. Why are we taking engineering cues from a glorified room rental site that is frequently buggy?
- redwards510 11y agoDon't think of it as advice from a crappy site. Think of it as developers at a big company sharing how they do things. Take what you want from it, or just use it as a conversation jumping off point.
- qq66 11y agoI've used AirBnB several times and never found it buggy enough to impair my main objective of booking a place to stay. It seems to be as robust as it needs to be.
- TheAceOfHearts 11y agoAs an alternative style guide, consider giving standard [0] a try. The hook is: "No decisions to make. No .eslintrc, .jshintrc, or .jscsrc files to manage. It just works." You don't have to configure anything, you just run it on your project and it'll tell you what to change. [0] https://github.com/feross/standard https://github.com/feross/standard
- berzniz 11y agoStyleguides are a matter of taste and there are probably no two people in the world with the same taste. Was there a voting of this?
- jasonkester 11y agoI think I'd go nuts in a codebase with their whitespace and brackets rules. Sure, cramming the opening bracket onto the previous line is just ugly and something you could learn to live with. But there's a special type of rage that can only be generated by clicking on to the start of a line and having your cursor land 1-2 spaces to the left of it. Why would anybody do that to their code voluntarily?
- thoman23 11y agoWait, are you saying that you put the opening bracket on the next line? That would drive me crazy.
- Ronsenshi 11y agoJust like it drives you crazy to put opening bracket on the same line - it drives other people crazy to put it on the next line.
- ggreer 11y agoSome style preferences are subjective, but some have very good reasons for being the way they are. Here's a simple JavaScript function that returns an object... function blah() { return { key: "value" }; } ...except it returns undefined when invoked: console.log(blah()); undefined Can you spot the bug? With so little code, it should be obvious, right? Before reading on, stop for a minute and really try to find the error. ... Figured it out? ... The answer is that JavaScript has automatic semicolon insertion. That means there's effectively a semicolon on the same line as return. ASI is why, in JavaScript, you always put the curly brace on the same line. Sure, you could try to remember the ASI rules, but you're guaranteed to be safe if you just put your braces on the same line. And considering how much code a typical programmer writes, you are almost guaranteed to inflict an ASI bug on yourself if you don't do this.
- mc808 11y agoAFAIK, return statements are literally the only place where brace style is affected by ASI. var result = { key: "value" }; return result; works fine, plus it lets you more easily break on the return statement and verify/modify what will be returned when debugging. It would be kind of awkward to see braces like that in JavaScript, but a style guide could just ban returning object literals and make the ASI issue moot (at least regarding braces; you still have the other gotchas with forgetting a comma in a variable declaration, etc).
- dkrvt 11y agoI'm curious as I haven't found a good coding style guide about object inheritance in ES5. I usually write this even though it's a bit verbose: function Child() { Parent.call(this); } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; Any opinion on this or link to a good guide?
- yefim 11y agoES6 actually solves this with it's new Class syntax. class Child extends Parent { }
- liviu 11y ago"Recommend using .jsx extension for React components, rather than .js" I like .js over .jsx because I can require/import without explicit extension. import Foo from './Foo'; vs import Foo from './Foo.jsx';
- Rygu 11y agoIf you're using webpack (who isn't?) then you can add .jsx to the known and attempted extensions. Although I prefer .js as well because there's eventually there's no reason to structure your JS codebase on extension-level. Better do it at the directory-level.
- fit2rule 11y agoGreat, so you'll never be quite sure whether that module is a plain ol' javascript, or contains React-extended components... eventually it'll all blend together and you won't have much awareness, say .. a year or so after you've put the code to bed .. what is where and how ..
- liviu 11y agoNot really. In a real-case scenario React-extended components stays in "components" directory and is not to hard to be aware that is react-extended component. But yes, I got your point.
- bshimmin 11y ago3.3 Use readable synonyms in place of reserved words. // bad const superman = { class: 'alien', }; // bad const superman = { klass: 'alien', }; What is unreadable about "klass"? Rails, for example, uses "klass" and it's never been hard for me (or, I suspect, anyone) to understand.
- cmrn 11y agoThe problem I see with "klass" is that you can't easily talk about it to another developer. e.g.: "Make sure you set the class-with-a-k property to 'alien'." "Make sure you set the type property to 'alien'."
- jbergens 11y agoThey probably don't mean 'class' in the programming language sense and should therefore use another name.
- adrusi 11y agoWell maybe they are using "class" in the OOP sense, for instance if they're implementing a programming language. Even if they're not, if they use the word "class" in the specification for what they're implementing (maybe they're representing a taxonomical hierarchy in their program and have fields named "kingdom", "phylum", "class", etc), or have the word "class" in a user facing output (maybe they're making an RPG where a character object has fields "race", "class", "level"). It's confufing to use one name inside your code and different one elsewhere.
- da4c30ff 11y ago3.5 Use object method shorthand. I disagree. With anonymous objects it breaks the syntactical uniformity of the expression. I think it is much clearer when each field is given a name(and a value) the same way.
- nailer 11y agoAlternatively, idiomatic.js https://github.com/rwaldron/idiomatic.js/ https://github.com/rwaldron/idiomatic.js/, an older publication with more people contributing to it.
- heydanreeves 11y agoThere's also a jscs default for this styleguide. { "preset": "airbnb" }
- lewisjoe 11y agohttp://stackoverflow.com/questions/21545687/javascript-vs-new-object-performance http://stackoverflow.com/questions/21545687/javascript-vs-ne... -explains why {} is better than new Object().
- ilaksh 11y agoSo basically they could have just written "use all of the new features except these three things..".
- neebz 11y agoDoes anybody have experience integrating style guides in your existing code base? Our old code base doesn't follow any style guide. After adding a style guide it requires us to go back and fix all our old files which is time consuming + kinda messes up with the git history.
- mik3y 11y agoYes: Check in a unittest that runs your linter, and check in the config as well (eg jshintrc). Tackle all the flagrant style issues until the test passes.
- z3t4 11y agoI love these kind of style guides. But I also love to prove them wrong. Unless you "use strict", it's better to put var in-front of every variable if you put them on separate lines. var foo = 1, bar = 2 baz = 3 vs var foo = 1; var bar = 2; var baz = 3; Forgetting a comma or semicolon in the first example might lead to silent bugs that will take hours to find.
- savanaly 11y agoIsn't this exact rule already in the guide? https://github.com/airbnb/javascript#13.2 https://github.com/airbnb/javascript#13.2
- z3t4 11y agoAhh, someone might just have added it to troll me, or I'm crazy.
- dugmartin 11y agoIf you add a lint checker, like jshint, to your build steps those kinds of bugs are found instantly. You can also add these specific style guide checks to your build steps using jscs (https://www.npmjs.com/package/jscs https://www.npmjs.com/package/jscs).
- z3t4 11y agoAbout referencing "this": It can be very useful when writing object constructors, if you always reference an object with the constructor's name. function Foo() { var foo = this; foo.bar = 1; foo.az = 2; } var foo = new Foo(); foo.bar = foo.bar + 5; Then it will be super easy to rename say foo.bar to something else. It's also self "documented".
- eltaco 11y agoYou can use the airbnb preset with JSCS (javascript code style checker) [1]. Also there's an autofix feature for most of the whitespace rules (`jscs src --preset=airbnb --fix`) so you won't have to fix everything manually. [1]: http://jscs.info/overview.html http://jscs.info/overview.html