###All code in any code-base should look like a single person typed it, no matter how many people contributed.### ###As a general rule of thumb, don't do stupid shit and everything will be ok.###
- Types
- Objects
- Arrays
- Strings
- Functions
- Properties
- Variables
- Hoisting
- Conditional Expressions & Equality
- Blocks
- Comments
- Whitespace
- Commas
- Semicolons
- Type Casting & Coercion
- Naming Conventions
- Accessors
- Constructors
- Events
- Modules
- Danger Zone
- Testing
- Resources
- License
-
Primitives: When you access a primitive type you work directly on its value
string
number
boolean
null
undefined
var foo = 1, bar = foo; bar = 9; console.log(foo, bar); // => 1, 9
-
Complex: When you access a complex type you work on a reference to its value
object
array
function
var foo = [1, 2], bar = foo; bar[0] = 9; console.log(foo[0], bar[0]); // => 9, 9
-
Use the literal syntax for object creation.
// bad var item = new Object(); // good var item = {};
-
Don't use reserved words as keys. It won't work in IE8. More info
// bad var superman = { default: { clark: 'kent' }, private: true }; // good var superman = { defaults: { clark: 'kent' }, hidden: true };
-
In instances where a reserved word must be used, for example
catch
, which is often a method on Promise objects, use subscript notation -
Note: this approach must only be followed when the code will run on the browser where IE8 compatability may be a concern
// bad asyncCall() .then(doSomething) .then(doSomethingElse) .catch(handleError); // good asyncCall() .then(doSomething) .then(doSomethingElse) ['catch'](handleError);
-
Use readable synonyms in place of reserved words.
// bad var superman = { class: 'alien' }; // bad var superman = { klass: 'alien' }; // good var superman = { type: 'alien' };
-
Use the literal syntax for array creation
// bad var items = new Array(); // good var items = [];
-
If you don't know an array's length use Array#push.
var someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
-
Use single quotes
''
for strings// bad var name = "Clark Kent"; // good var name = 'Clark Kent'; // bad var fullName = "Clark " + this.lastName; // good var fullName = 'Clark ' + this.lastName;
-
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
// bad var errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.'; // bad var errorMessage = 'This is a super long error that was thrown because \ of Batman. When you stop to think about how Batman had anything to do \ with this, you would get nowhere \ fast.'; // good var errorMessage = 'This is a super long error that was thrown because ' + 'of Batman. When you stop to think about how Batman had anything to do ' + 'with this, you would get nowhere fast.';
-
Function expressions:
// anonymous function expression var anonymous = function() { return true; }; // named function expression var named = function named() { return true; }; // immediately-invoked function expression (IIFE) (function() { console.log('Welcome to the Internet. Please follow me.'); })();
-
Function declaration:
function declaredName() { return true; }
-
Do not define and pass in functions as callbacks within the argument list. Instead use a named function declaration and pass the name reference.
// bad asyncCall(foo, function(err, result) { // ...stuff... }); // good asyncCall(foo, handleResponse); function handleResponse(err, result) { // ...stuff... }
-
Unless an IIFE is being used to create a closure or scope, all functions should be named via the function declaration syntax. Anonymous functions will display as such in the error call stack, so naming a function will provide better error reporting. Function declarations get hoisted, so they can be accessed from anywhere within the lexical scope, even above their definition (see Hoisting for more information).
-
Never declare a function in a non-function block (if, while, etc).
-
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.// bad if (currentUser) { function test() { console.log('Nope.'); } } // good if (currentUser) { // ...stuff... } function test() { console.log('Yup.'); }
-
Never name a parameter
arguments
, this will take precedence over thearguments
object that is given to every function scope. -
Give paramaters meaningful names over abstract ones (see Naming Conventions).
// bad function nope(name, options, arguments) { // ...stuff... } // good function yup(name, options, args) { // ...stuff... } // best function yup(name, options, config) { // ...stuff... }
-
The return value must be on the same line as the return keyword in order to avoid semicolon insertion.
// bad function foo() { return 'bar'; } foo() // => undefined // good function foo() { return 'bar'; } foo() // => 'bar'
-
Use dot notation when accessing properties.
var luke = { jedi: true, age: 28 }; // bad var isJedi = luke['jedi']; // good var isJedi = luke.jedi;
-
Use subscript notation
[]
when accessing properties with a variable (or when a reserved word must be used -- see the Objects section).var luke = { jedi: true, age: 28 }; function getProp(prop) { return luke[prop]; } var isJedi = getProp('jedi');
-
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.// bad superPower = new SuperPower(); // good var superPower = new SuperPower();
-
Use one
var
declaration for multiple variables within the same scope and declare each variable on a newline.// bad var items = getItems(); var goSportsTeam = true; var dragonball = 'z'; // good var items = getItems(), goSportsTeam = true, dragonball = 'z';
-
Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
// bad var i, len, dragonball, items = getItems(), goSportsTeam = true; // bad var i, items = getItems(), dragonball, goSportsTeam = true, len; // good var items = getItems(), goSportsTeam = true, dragonball, length, i;
-
Avoid large variable assignments when declaring multiple variables.
// bad var superHeroes = { superman: 'Clark Kent', bathman: 'Bruce Wayne', greenLantern: 'Hal Jordan', ironman: 'Tony Stark' }, superVillains = [ 'Lex Luther', 'Joker', 'Sinestro', 'Mandarin' ]; // good var superHeroes, superVillains; superHeroes = { superman: 'Clark Kent', bathman: 'Bruce Wayne', greenLantern: 'Hal Jordan', ironman: 'Tony Stark' }; superVillains = [ 'Lex Luther', 'Joker', 'Sinestro', 'Mandarin' ];
-
Assign variables at the top of their scope (if you have variables, the
var
statement should be the first statement in the function body). This helps avoid issues with variable declaration and assignment hoisting related issues.// bad function() { test(); console.log('doing stuff..'); //..other stuff.. var name = getName(); if (name === 'test') { return false; } return name; } // good function() { var name = getName(); test(); console.log('doing stuff..'); //..other stuff.. if (name === 'test') { return false; } return name; } // bad function() { var name = getName(); if (!arguments.length) { return false; } return true; } // good function() { var name; if (!arguments.length) { return false; } name = getName(); return true; }
-
const
andlet
, from ES6, should also be assigned at the top of their block scope// bad function foo() { let foo, bar; if (condition) { bar = 'baz'; // statements } } // good function foo() { let foo; if (condition) { let bar = 'baz'; // statements } }
-
Variable declarations get hoisted to the top of their scope, their assignment does not.
// we know this wouldn't work (assuming there // is no notDefined global variable) function example() { console.log(notDefined); // => throws a ReferenceError } // creating a variable declaration after you // reference the variable will work due to // variable hoisting. Note: the assignment // value of `true` is not hoisted. function example() { console.log(declaredButNotAssigned); // => undefined var declaredButNotAssigned = true; } // The interpreter is hoisting the variable // declaration to the top of the scope. // Which means our example could be rewritten as: function example() { var declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true; }
-
Anonymous function expressions hoist their variable name, but not the function assignment.
function example() { console.log(anonymous); // => undefined anonymous(); // => TypeError anonymous is not a function var anonymous = function() { console.log('anonymous function expression'); }; }
-
Named function expressions hoist the variable name, not the function name or the function body.
function example() { console.log(named); // => undefined named(); // => TypeError named is not a function superPower(); // => ReferenceError superPower is not defined var named = function superPower() { console.log('Flying'); }; } // the same is true when the function name // is the same as the variable name. function example() { console.log(named); // => undefined named(); // => TypeError named is not a function var named = function named() { console.log('named'); } }
-
Function declarations hoist their name and the function body.
function example() { superPower(); // => Flying function superPower() { console.log('Flying'); } }
-
For more information refer to JavaScript Scoping & Hoisting by Ben Cherry
-
Use
===
and!==
over==
and!=
. -
Conditional expressions are evaluated using coercion with the
ToBoolean
method and always follow these simple rules:- Objects evaluate to true
- Undefined evaluates to false
- Null evaluates to false
- Booleans evaluate to the value of the boolean
- Numbers evaluate to false if +0, -0, or NaN, otherwise true
- Strings evaluate to false if an empty string
''
, otherwise true
if ([0]) { // true // An array is an object, objects evaluate to true }
-
Avoid doing assignments as part of a conditional.
// bad if (a = b) { // ...stuff... } // good a = b; if (a) { // ...stuff... }
-
Use shortcuts.
// Strings // bad if (name !== '') { // ...stuff... } if (otherName === '') { // ...stuff... } // good if (name) { // ...stuff... } if (!otherName) { // ...stuff... } // Booleans // bad if (foo === true) { // ...stuff... } if (bar === false) { // ...stuff... } // good if (foo) { // ...stuff... } if (!bar) { // ...stuff... } // Array Length // bad if (collection.length > 0) { // ...stuff... } if (otherCollection.length === 0) { // ...stuff... } // good if (collection.length) { // ...stuff... } if (!otherCollection.length) { // ...stuff... } // Null and Undefined // When only evaluating a ref that might be null or undefined, but NOT false, "" or 0, if (foo === null || foo === undefined) { // ...stuff... }
-
For more information see Truth Equality and JavaScript by Angus Croll
-
Use braces with all multi-line blocks.
// bad if (test) return false; // good if (test) return false; // best if (test) { return false; } // bad function() { return false; } // good function() { return false; }
-
Use
/** ... */
for multiline comments.// bad // make() returns a new element // based on the passed in tag name function make(tag) { // ...stuff... return element; } // good /** * make() returns a new element * based on the passed in tag name */ function make(tag) { // ...stuff... return element; }
-
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.// bad var active = true; // is current tab // good // is current tab var active = true; // bad function getType() { console.log('fetching type...'); // set the default type to 'no type' var type = this._type || 'no type'; return type; } // good function getType() { console.log('fetching type...'); // set the default type to 'no type' var type = this._type || 'no type'; return type; }
-
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 problemsfunction Calculator() { // FIXME: shouldn't use a global here total = 0; return this; }
-
Use
// TODO:
to annotate solutions to problemsfunction Calculator() { // TODO: total should be configurable by an options param this.total = 0; return this; }
**[⬆ back to top](#table-of-contents)**
## Whitespace
- Never mix spaces and tabs
- Use soft tabs set to 2 spaces
```javascript
// bad
function() {
∙∙∙∙var name;
}
// bad
function() {
∙var name;
}
// good
function() {
∙∙var name;
}
```
- Remove trailing whitespace
```javascript
// bad
var foo = 'bar';∙
// good
var foo = 'bar';
```
- For non-function statements (e.g., if/while/for), place 1 space between the
statement and the leading paren
```javascript
//bad
if(condition){
// ...stuff...
}
while(condition){
// ...stuff...
}
//good
if (condition) {
// ...stuff...
}
while (condition) {
// ...stuff...
}
```
- Place 1 space between paramaters
```javascript
// bad
foo(bar,baz);
for (var i=0;i<100;i++) {
someIterativeFn();
}
// good
foo(bar, baz);
for (var i = 0; i < 100; i++) {
// ...stuff...
}
```
- Place 1 space before the leading brace.
```javascript
// bad
function test(){
console.log('test');
}
// good
function test() {
console.log('test');
}
// bad
dog.set('attr',{
age: '1 year',
breed: 'Bernese Mountain Dog'
});
// good
dog.set('attr', {
age: '1 year',
breed: 'Bernese Mountain Dog'
});
```
- Set off operators with spaces.
```javascript
// bad
var x=y+5;
// good
var x = y + 5;
```
- End files with a single newline character.
```javascript
// bad
(function(global) {
// ...stuff...
})(this);
```
```javascript
// bad
(function(global) {
// ...stuff...
})(this);↵
↵
```
```javascript
// good
(function(global) {
// ...stuff...
})(this);↵
```
- Use indentation when making long method chains.
```javascript
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
// bad
var leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true)
.attr('width', (radius + margin) * 2).append('svg:g')
.attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
.call(tron.led);
// good
var leds = stage.selectAll('.led')
.data(data)
.enter().append('svg:svg')
.class('led', true)
.attr('width', (radius + margin) * 2)
.append('svg:g')
.attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
.call(tron.led);
```
- Insert a newline after functions and label statements.
```javascript
// bad
if (condition) {
} else {
}
try {
} catch(e) {
}
// good
if (condition) {
}
else {
}
try {
}
catch(e) {
}
```
- Indent the `case` statements of a `switch`.
```javascript
// bad
switch (foo) {
case 'bar':
// ...stuff...
break;
case 'baz':
// ...stuff...
break;
default:
// ...stuff...
break;
}
// good
switch (foo) {
case 'bar':
// ...stuff...
break;
case 'baz':
// ...stuff...
break;
default:
// ...stuff...
break;
}
```
**[⬆ back to top](#table-of-contents)**
## Commas
- Leading commas: **Nope.**
```javascript
// bad
var
once
, upon
, aTime;
// good
var
once,
upon,
aTime;
// bad
var hero = {
firstName: 'Clark'
, lastName: 'Kent'
, heroName: 'Superman'
, superPower: 'everything'
};
// good
var hero = {
firstName: 'Clark',
lastName: 'Ken',
heroName: 'Superman',
superPower: 'everything'
};
```
- 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](http://es5.github.io/#D)):
> Edition 5 clarifies the fact that a trailing comma at the end of an ArrayInitialiser does not add to the length of the array. This is not a semantic change from Edition 3 but some implementations may have previously misinterpreted this.
```javascript
// bad
var hero = {
firstName: 'Kevin',
lastName: 'Flynn',
};
var heroes = [
'Batman',
'Superman',
];
// good
var hero = {
firstName: 'Kevin',
lastName: 'Flynn'
};
var heroes = [
'Batman',
'Superman'
];
```
**[⬆ back to top](#table-of-contents)**
## Semicolons
- **Yup.**
```javascript
// bad
(function() {
var name = 'Skywalker'
return name
})()
// good
(function() {
var name = 'Skywalker';
return name;
})();
// good (guards against the function becoming an argument when two files with IIFEs are concatenated)
;(function() {
var name = 'Skywalker';
return name;
})();
```
[Read more](http://stackoverflow.com/a/7365214/1712802).
**[⬆ back to top](#table-of-contents)**
## Type Casting & Coercion
- Common types of coercion
```javascript
var
number = 1,
string = '1',
bool = false;
number; // => 1
'' + number; // => '1'
!!number; // => true
string; // => '1'
+string; // => 1
// NOTE: Always prefer #parseInt to + as noted below
string; // => '1'
+string++; // => 1
string; // => 2
bool; // => false
+bool; // => 0
'' + bool; // => 'false'
```
- Perform type coercion at the beginning of the statement.
- Strings:
```javascript
// => 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';
```
- Use `parseInt` for Numbers and always with a radix for type casting.
```javascript
var inputValue = '4';
// bad
var val = new Number(inputValue);
// bad
var val = +inputValue;
// bad
var val = inputValue >> 0;
// bad
var val = parseInt(inputValue);
// good
var val = Number(inputValue);
// best
var val = parseInt(inputValue, 10);
```
- If for whatever reason you are doing something wild and `parseInt` is your bottleneck and need to use Bitshift for [performance reasons](http://jsperf.com/coercion-vs-casting/3), leave a comment explaining why and what you're doing.
```javascript
// good
/**
* parseInt was the reason my code was slow.
* Bitshifting the String to coerce it to a
* Number made it a lot faster.
*/
var val = inputValue >> 0;
```
- **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
```javascript
2147483647 >> 0 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
```
- Booleans:
```javascript
var age = 0;
// bad
var hasAge = new Boolean(age);
// good
var hasAge = Boolean(age);
// best
var hasAge = !!age;
```
**[⬆ back to top](#table-of-contents)**
## Naming Conventions
- Avoid single letter names. Be descriptive with your naming.
```javascript
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
```
- Use camelCase when naming objects, functions, and instances
```javascript
// bad
var OBJEcttsssss = {};
var this_is_my_object = {};
function c() {}
var u = new user({
name: 'Clark Kent'
});
// good
var thisIsMyObject = {};
function thisIsMyFunction() {}
var user = new User({
name: 'Clark Kent'
});
```
- Use PascalCase when naming constructors or classes
```javascript
// bad
function user(options) {
this.name = options.name;
}
var bad = new user({
name: 'nope'
});
// good
function User(options) {
this.name = options.name;
}
var good = new User({
name: 'yup'
});
```
- Use a leading underscore `_` when naming private properties in constructors or classes
```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
```
- When saving a reference to `this` use `_this`.
- **Note:** This is extremely bug prone and should only be done as a last resort. If you find you are having troubles with `this` being set to the wrong context, consider using the `#call`, `#apply` or `#bind` functions, or
check the documentation to see if a `thisArg` can be passed into a function call.
```javascript
// 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);
};
}
```
- Name your functions. This is helpful for stack traces.
```javascript
// bad
var log = function(msg) {
console.log(msg);
};
// good
var log = function log(msg) {
console.log(msg);
};
// best (function declaration)
function log(msg) {
console.log(msg);
};
```
**[⬆ back to top](#table-of-contents)**
## Accessors
- Accessor functions for properties are not required
- If you do make accessor functions use getVal() and setVal('hello')
```javascript
// bad
dragon.age();
// good
dragon.getAge();
// bad
dragon.age(25);
// good
dragon.setAge(25);
```
- If the property is a boolean, use isVal() or hasVal()
```javascript
// bad
if (!dragon.age()) {
return false;
}
// good
if (!dragon.hasAge()) {
return false;
}
```
- It's okay to create get() and set() functions, but be consistent.
```javascript
function Jedi(options) {
options || (options = {});
var lightsaber = options.lightsaber || 'blue';
this.set('lightsaber', lightsaber);
}
Jedi.prototype.set = function(key, val) {
this[key] = val;
};
Jedi.prototype.get = function(key) {
return this[key];
};
```
- Use the ES5 `get` and `set` keywords to define getters and setters in a more intuitive way as
if they were properties, though they are in fact functions
- **Note:** IE8 and below support is not available for this convention. For more information see [http://ejohn.org/blog/javascript-getters-and-setters/](http://ejohn.org/blog/javascript-getters-and-setters/)
```javascript
function Dragon() {
var age = 500;
return {
get age() {
return age;
},
set age(newValue) {
age = newValue;
}
};
}
var dragon = Dragon();
console.log(dragon.age) // => 500
dragon.age = 1000;
console.log(dragon.age) // => 1000
```
**[⬆ back to top](#table-of-contents)**
## 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!
```javascript
function Jedi() {
this.message = 'new jedi';
console.log(message);
return this;
/**
* when creating a constructor to be instatiated via the `new` keyword,
* there is an implicit return of `this`, however it is better to be
* explicit.
*/
}
// bad
Jedi.prototype = {
fight: function fight() {
console.log('fighting');
},
block: function block() {
console.log('blocking');
}
};
// good
Jedi.prototype.fight = function fight() {
console.log('fighting');
};
Jedi.prototype.block = function block() {
console.log('blocking');
};
```
- Methods can return `this` to help with method chaining.
```javascript
// bad
Jedi.prototype.jump = function() {
this.jumping = true;
return true;
};
Jedi.prototype.setHeight = function(height) {
this.height = height;
};
var luke = new Jedi();
luke.jump(); // => true
luke.setHeight(20) // => undefined
// good
Jedi.prototype.jump = function() {
this.jumping = true;
return this;
};
Jedi.prototype.setHeight = function(height) {
this.height = height;
return this;
};
var luke = new Jedi();
luke.jump()
.setHeight(20);
```
- It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.
```javascript
function Jedi(options) {
options || (options = {});
this.name = options.name || 'no name';
}
Jedi.prototype.getName = function getName() {
return this.name;
};
Jedi.prototype.toString = function toString() {
return 'Jedi - ' + this.getName();
};
```
**[⬆ back to top](#table-of-contents)**
## 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:
```js
// bad
$(this).trigger('listingUpdated', listing.id);
...
$(this).on('listingUpdated', function(e, listingId) {
// do something with listingId
});
```
prefer:
```js
// good
$(this).trigger('listingUpdated', { listingId : listing.id });
...
$(this).on('listingUpdated', function(e, data) {
// do something with data.listingId
});
```
**[⬆ back to top](#table-of-contents)**
## Modules
- The file should be named with snake case and match the name of the single export written in camel case.
- Always declare `'use strict';` at the top of the module.
```javascript
// Node module
// fancy_input/fancy_input.js
module.exports = FancyInput;
function FancyInput() {
'use strict';
function doSomethingFancy(options) {
options = options || {};
return true;
}
return {
doSomethingFancy: doSomethingFancy
};
}
// Client-side module
(function(global) {
'use strict';
global.FancyModule = FancyModule;
function FancyModule() {
var
data = "secret",
myArray = [ 1, 2, 3, 4 ];
return {
myArray: myArray,
doSomething: doSomething,
doSomethingElse: doSomethingElse
};
function doSomething() {
// ...stuff...
}
function doSomethingElse() {
// ...stuff...
}
}
})(this);
```
**[⬆ back to top](#table-of-contents)**
## jQuery
- Prefix jQuery object variables with a `$`.
```javascript
// bad
var sidebar = $('.sidebar');
// good
var $sidebar = $('.sidebar');
```
- Cache jQuery lookups.
```javascript
// bad
function setSidebar() {
$('.sidebar').hide();
// ...stuff...
$('.sidebar').css({
'background-color': 'pink'
});
}
// good
function setSidebar() {
var $sidebar = $('.sidebar');
$sidebar.hide();
// ...stuff...
$sidebar.css({
'background-color': 'pink'
});
}
```
- For DOM queries use Cascading `$('.sidebar ul')` or parent > child `$('.sidebar > ul')`. [jsPerf](http://jsperf.com/jquery-find-vs-context-sel/16)
- Use `find` with scoped jQuery object queries.
```javascript
// bad
$('ul', '.sidebar').hide();
// bad
$('.sidebar').find('ul').hide();
// good
$('.sidebar ul').hide();
// good
$('.sidebar > ul').hide();
// good
$sidebar.find('ul').hide();
```
**[⬆ back to top](#table-of-contents)**
## Danger Zone
- `#eval`. Do not use it. It is insecure, can be difficult to debug, and is slow.
- `with`. No.
- `delete`. Avoid if possible due to performance issues. Often the same objective can be achieved by setting the object property to `null` or `undefined`.
- You should not be modifying the `prototype` of built in objects (e.g., `Object.prototype` or `Array.prototype`). Prefer creating a helper utility instead (e.g., the lo-dash library, which provides convenience methods for working with arrays and objects)
**[⬆ back to top](#table-of-contents)**
## Testing
- **Yup.**
+ [Jasmine testing framework](http://jasmine.github.io/2.0/introduction.html)
+ [Karma test runner](http://karma-runner.github.io/0.12/index.html)
+ [Protractor e2e framework and runner](https://github.com/angular/protractor)
+ [Istanbul code coverage](http://gotwarlost.github.io/istanbul/)
**[⬆ back to top](#table-of-contents)**
## Resources
**Read This**
- [Annotated ECMAScript 5.1](http://es5.github.com/)
**Tools**
- Code Style Linters
+ [JSHint](http://www.jshint.com/) - [Airbnb Style .jshintrc](https://github.com/airbnb/javascript/blob/master/linters/jshintrc)
+ [JSCS](https://github.com/jscs-dev/node-jscs) - [Airbnb Style Preset](https://github.com/jscs-dev/node-jscs/blob/master/presets/airbnb.json)
**Other Styleguides**
- [Google JavaScript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml)
- [jQuery Core Style Guidelines](http://docs.jquery.com/JQuery_Core_Style_Guidelines)
- [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwldrn/idiomatic.js/)
**Other Styles**
- [Naming this in nested functions](https://gist.github.com/4135065) - Christian Johansen
- [Conditional Callbacks](https://github.com/airbnb/javascript/issues/52) - Ross Allen
- [Popular JavaScript Coding Conventions on Github](http://sideeffect.kr/popularconvention/#javascript) - JeongHoon Byun
- [Multiple var statements in JavaScript, not superfluous](http://benalman.com/news/2012/05/multiple-var-statements-javascript/) - Ben Alman
**Further Reading**
- [Understanding JavaScript Closures](http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/) - Angus Croll
- [Basic JavaScript for the impatient programmer](http://www.2ality.com/2013/06/basic-javascript.html) - Dr. Axel Rauschmayer
- [You Might Not Need jQuery](http://youmightnotneedjquery.com/) - Zack Bloom & Adam Schwartz
- [ES6 Features](https://github.com/lukehoban/es6features) - Luke Hoban
**Books**
- [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) - Douglas Crockford
- [JavaScript Patterns](http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752) - Stoyan Stefanov
- [Pro JavaScript Design Patterns](http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X) - Ross Harmes and Dustin Diaz
- [High Performance Web Sites: Essential Knowledge for Front-End Engineers](http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309) - Steve Souders
- [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680) - Nicholas C. Zakas
- [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X) - Alex MacCaw
- [Pro JavaScript Techniques](http://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273) - John Resig
- [Smashing Node.js: JavaScript Everywhere](http://www.amazon.com/Smashing-Node-js-JavaScript-Everywhere-Magazine/dp/1119962595) - Guillermo Rauch
- [Secrets of the JavaScript Ninja](http://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/193398869X) - John Resig and Bear Bibeault
- [Human JavaScript](http://humanjavascript.com/) - Henrik Joreteg
- [Superhero.js](http://superherojs.com/) - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy
- [JSBooks](http://jsbooks.revolunet.com/) - Julien Bouquillon
- [Third Party JavaScript](http://manning.com/vinegar/) - Ben Vinegar and Anton Kovalyov
**Blogs**
- [DailyJS](http://dailyjs.com/)
- [JavaScript Weekly](http://javascriptweekly.com/)
- [JavaScript, JavaScript...](http://javascriptweblog.wordpress.com/)
- [Bocoup Weblog](http://weblog.bocoup.com/)
- [Adequately Good](http://www.adequatelygood.com/)
- [NCZOnline](http://www.nczonline.net/)
- [Perfection Kills](http://perfectionkills.com/)
- [Ben Alman](http://benalman.com/)
- [Dmitry Baranovskiy](http://dmitry.baranovskiy.com/)
- [Dustin Diaz](http://dustindiaz.com/)
- [nettuts](http://net.tutsplus.com/?s=javascript)
**[⬆ back to top](#table-of-contents)**
## 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](#table-of-contents)**