-
Notifications
You must be signed in to change notification settings - Fork 11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Write a Chapter: "Our JavaScript Style Guide" #13
Comments
I think Andrew mentioned that. I dig the idea. |
I'm in general a big fan of strict style checkers and static analysis. The one thing that I'd like to see even more than the style guide document is a set of JSCS / JSHINT config files that enforce them. |
@thisandagain We'll be doing that in Unicorn. 👍 See: |
Also, we'll be enforcing via Travis. |
Great on both. Thanks @gvn |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Airbnb JavaScript Style Guide() {
A mostly reasonable approach to JavaScript
Table of Contents
Types
Primitives: When you access a primitive type you work directly on its value
string
number
boolean
null
undefined
Complex: When you access a complex type you work on a reference to its value
object
array
function
⬆ back to top
undefined
undefined
is an object. You should use it as an object. You can test for it. For instance:Only use
typeof x == "undefined"
when the variable (x
) may not be declared, and it would be an error to testx === undefined
:Note that you can't use
window
in Node.js; if you think your code could be used in a server context you should use the first form.⬆ back to top
Objects
Use the literal syntax for object creation.
Note that you can't use
window
in Node.js; if you think your code could be used in a server context you should use the first form.⬆ back to top
Objects
Use the literal syntax for object creation.
As an example that reserved words are both okay right now and will be indefinitely, the IndexedDB API uses
cursor.continue()
⬆ back to top
Arrays
Use the literal syntax for array creation
If you don't know array length use Array#push.
When you need to copy an array use Array#slice. jsPerf
To convert an array-like object to an array, use Array#slice.
⬆ back to top
Strings
Use single or double quotes (
'
or"
) for strings. There is a slight preference for double-quotes, aligning with Mozilla style.Strings longer than 80 characters should be written across multiple lines using string concatenation.
Note: If overused, long strings with concatenation could impact performance. jsPerf & Discussion
When programmatically building up a string, use Array#join instead of string concatenation. Mostly for IE: jsPerf.
⬆ back to top
Functions
Function expressions:
Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.
Note: ECMA-262 defines a
block
as a list of statements. A function declaration is not a statement. Read ECMA-262's note on this issue.Never name a parameter
arguments
, this will take precedence over thearguments
object that is given to every function scope.⬆ back to top
Properties
Use dot notation when accessing properties.
Use subscript notation
[]
when accessing properties with a variable.⬆ back to top
Variables
Always use
var
to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.Use one
var
declaration per variable and declare each variable on a newline.Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.
As an exception, declaring a variable in a
for
loop is common and okay.⬆ back to top
Hoisting
Variable declarations get hoisted to the top of their scope, their assignment does not.
Anonymous function expressions hoist their variable name, but not the function assignment.
Named function expressions hoist the variable name, not the function name or the function body.
Function declarations hoist their name and the function body.
For more information refer to JavaScript Scoping & Hoisting by Ben Cherry
⬆ back to top
Conditional Expressions & Equality
Use
===
and!==
over==
and!=
.Conditional expressions are evaluated using coercion with the
ToBoolean
method and always follow these simple rules:''
, otherwise trueUse shortcuts.
For more information see Truth Equality and JavaScript by Angus Croll
⬆ back to top
Blocks
Use braces with all multi-line blocks.
⬆ back to top
Comments
Use
/** ... */
for multiline comments. Include a description, specify types and values for all parameters and return values.Use
//
for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment.Prefixing your comments with
FIXME
orTODO
helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions areFIXME -- need to figure this out
orTODO -- need to implement
.Use
// FIXME:
to annotate problemsUse
// TODO:
to annotate solutions to problems⬆ back to top
Whitespace
Use soft tabs set to 2 spaces
Place 1 space before the leading brace.
Set off operators with spaces.
End files with a single newline character.
Use indentation when making long method chains.
⬆ back to top
Commas
Leading commas: Nope.
Additional trailing comma: Nope. This can cause problems with IE6/7 and IE9 if it's in quirksmode. Also, in some implementations of ES3 would add length to an array if it had an additional trailing comma. This was clarified in ES5 (source):
⬆ back to top
Semicolons
Yup.
Read more.
⬆ back to top
Type Casting & Coercion
Perform type coercion at the beginning of the statement.
Strings:
Use
parseInt
for Numbers and always with a radix for type casting.If for whatever reason you are doing something wild and
parseInt
is your bottleneck and need to use Bitshift for performance reasons, leave a comment explaining why and what you're doing.Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values, but Bitshift operations always return a 32-bit integer (source). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion. Largest signed 32-bit Int is 2,147,483,647:
Booleans:
⬆ back to top
Naming Conventions
Avoid single letter names. Be descriptive with your naming.
Use camelCase when naming objects, functions, and instances
Use PascalCase when naming constructors or classes
When saving a reference to
this
useself
.Name your functions. This is helpful for stack traces.
Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.
⬆ back to top
Accessors
Accessor functions for properties are not required
If the property is a boolean, use isVal() or hasVal()
It's okay to create get() and set() functions, but be consistent.
⬆ back to top
Constructors
Assign methods to the prototype object, instead of overwriting the prototype with a new object. Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base!
Methods can return
this
to help with method chaining.It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.
⬆ back to top
Events
When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:
prefer:
⬆ back to top
Modules
The module should start with a
!
. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated. ExplanationThe file should be named with camelCase, live in a folder with the same name, and match the name of the single export.
Add a method called
noConflict()
that sets the exported module to the previous version and returns this one.Always declare
'use strict';
at the top of the module.⬆ back to top
jQuery
Cache jQuery lookups.
For DOM queries use Cascading
$('.sidebar ul')
or parent > child$('.sidebar > ul')
. jsPerfUse
find
with scoped jQuery object queries.⬆ back to top
ECMAScript 5 Compatibility
⬆ back to top
Testing
Yup.
⬆ back to top
Performance
⬆ back to top
Resources
Read This
Other Styleguides
Other Styles
Further Reading
Books
Blogs
⬆ back to top
In the Wild
This is a list of organizations that are using this style guide. Send us a pull request or open an issue and we'll add you to the list.
Translation
This style guide is also available in other languages:
The JavaScript Style Guide Guide
Contributors
License
(The MIT License)
Copyright (c) 2014 Airbnb
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
⬆ back to top
};
The text was updated successfully, but these errors were encountered: