Files
javascript/params.json
2013-01-28 10:32:58 -08:00

1 line
35 KiB
JSON

{"body":"# Airbnb JavaScript Style Guide() {\r\n\r\n*A mostly reasonable approach to JavaScript*\r\n\r\n\r\n## <a name='TOC'>Table of Contents</a>\r\n\r\n 1. [Types](#types)\r\n 1. [Objects](#objects)\r\n 1. [Arrays](#arrays)\r\n 1. [Strings](#strings)\r\n 1. [Functions](#functions)\r\n 1. [Properties](#properties)\r\n 1. [Variables](#variables)\r\n 1. [Hoisting](#hoisting)\r\n 1. [Conditional Expressions & Equality](#conditionals)\r\n 1. [Blocks](#blocks)\r\n 1. [Comments](#comments)\r\n 1. [Whitespace](#whitespace)\r\n 1. [Leading Commas](#leading-commas)\r\n 1. [Semicolons](#semicolons)\r\n 1. [Type Casting & Coercion](#type-coercion)\r\n 1. [Naming Conventions](#naming-conventions)\r\n 1. [Accessors](#accessors)\r\n 1. [Constructors](#constructors)\r\n 1. [Modules](#modules)\r\n 1. [jQuery](#jquery)\r\n 1. [ES5 Compatibility](#es5)\r\n 1. [Testing](#testing)\r\n 1. [Performance](#performance)\r\n 1. [Resources](#resources)\r\n 1. [In the Wild](#in-the-wild)\r\n 1. [The JavaScript Style Guide Guide](#guide-guide)\r\n 1. [Contributors](#contributors)\r\n 1. [License](#license)\r\n\r\n## <a name='types'>Types</a>\r\n\r\n - **Primitives**: When you access a primitive type you work directly on its value\r\n\r\n + `string`\r\n + `number`\r\n + `boolean`\r\n + `null`\r\n + `undefined`\r\n\r\n ```javascript\r\n var foo = 1,\r\n bar = foo;\r\n\r\n bar = 9;\r\n\r\n console.log(foo, bar); // => 1, 9\r\n ```\r\n - **Complex**: When you access a complex type you work on a reference to its value\r\n\r\n + `object`\r\n + `array`\r\n + `function`\r\n\r\n ```javascript\r\n var foo = [1, 2],\r\n bar = foo;\r\n\r\n bar[0] = 9;\r\n\r\n console.log(foo[0], bar[0]); // => 9, 9\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n## <a name='objects'>Objects</a>\r\n\r\n - Use the literal syntax for object creation.\r\n\r\n ```javascript\r\n // bad\r\n var item = new Object();\r\n\r\n // good\r\n var item = {};\r\n ```\r\n\r\n - Don't use [reserved words](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Reserved_Words) as keys.\r\n\r\n ```javascript\r\n // bad\r\n var superman = {\r\n class: 'superhero',\r\n default: { clark: 'kent' },\r\n private: true\r\n };\r\n\r\n // good\r\n var superman = {\r\n klass: 'superhero',\r\n defaults: { clark: 'kent' },\r\n hidden: true\r\n };\r\n ```\r\n **[[⬆]](#TOC)**\r\n\r\n## <a name='arrays'>Arrays</a>\r\n\r\n - Use the literal syntax for array creation\r\n\r\n ```javascript\r\n // bad\r\n var items = new Array();\r\n\r\n // good\r\n var items = [];\r\n ```\r\n\r\n - If you don't know array length use Array#push.\r\n\r\n ```javascript\r\n var someStack = [];\r\n\r\n\r\n // bad\r\n someStack[someStack.length] = 'abracadabra';\r\n\r\n // good\r\n someStack.push('abracadabra');\r\n ```\r\n\r\n - When you need to copy an array use Array#slice. [jsPerf](http://jsperf.com/converting-arguments-to-an-array/7)\r\n\r\n ```javascript\r\n var len = items.length,\r\n itemsCopy = [],\r\n i;\r\n\r\n // bad\r\n for (i = 0; i < len; i++) {\r\n itemsCopy[i] = items[i];\r\n }\r\n\r\n // good\r\n itemsCopy = Array.prototype.slice.call(items);\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='strings'>Strings</a>\r\n\r\n - Use single quotes `''` for strings\r\n\r\n ```javascript\r\n // bad\r\n var name = \"Bob Parr\";\r\n\r\n // good\r\n var name = 'Bob Parr';\r\n\r\n // bad\r\n var fullName = \"Bob \" + this.lastName;\r\n\r\n // good\r\n var fullName = 'Bob ' + this.lastName;\r\n ```\r\n\r\n - Strings longer than 80 characters should be written across multiple lines using string concatenation.\r\n - Note: If overused, long strings with concatenation could impact performance. [jsPerf](http://jsperf.com/ya-string-concat) & [Discussion](https://github.com/airbnb/javascript/issues/40)\r\n\r\n ```javascript\r\n // bad\r\n 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.';\r\n\r\n // bad\r\n var errorMessage = 'This is a super long error that \\\r\n was thrown because of Batman. \\\r\n When you stop to think about \\\r\n how Batman had anything to do \\\r\n with this, you would get nowhere \\\r\n fast.';\r\n\r\n\r\n // good\r\n var errorMessage = 'This is a super long error that ' +\r\n 'was thrown because of Batman.' +\r\n 'When you stop to think about ' +\r\n 'how Batman had anything to do ' +\r\n 'with this, you would get nowhere ' +\r\n 'fast.';\r\n ```\r\n\r\n - When programatically building up a string, use Array#join instead of string concatenation. Mostly for IE: [jsPerf](http://jsperf.com/string-vs-array-concat/2).\r\n\r\n ```javascript\r\n var items,\r\n messages,\r\n length, i;\r\n\r\n messages = [{\r\n state: 'success',\r\n message: 'This one worked.'\r\n },{\r\n state: 'success',\r\n message: 'This one worked as well.'\r\n },{\r\n state: 'error',\r\n message: 'This one did not work.'\r\n }];\r\n\r\n length = messages.length;\r\n\r\n // bad\r\n function inbox(messages) {\r\n items = '<ul>';\r\n\r\n for (i = 0; i < length; i++) {\r\n items += '<li>' + messages[i].message + '</li>';\r\n }\r\n\r\n return items + '</ul>';\r\n }\r\n\r\n // good\r\n function inbox(messages) {\r\n items = [];\r\n\r\n for (i = 0; i < length; i++) {\r\n items[i] = messages[i].message;\r\n }\r\n\r\n return '<ul><li>' + items.join('</li><li>') + '</li></ul>';\r\n }\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='functions'>Functions</a>\r\n\r\n - Function expressions:\r\n\r\n ```javascript\r\n // anonymous function expression\r\n var anonymous = function() {\r\n return true;\r\n };\r\n\r\n // named function expression\r\n var named = function named() {\r\n return true;\r\n };\r\n\r\n // immediately-invoked function expression (IIFE)\r\n (function() {\r\n console.log('Welcome to the Internet. Please follow me.');\r\n })();\r\n ```\r\n\r\n - 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.\r\n - **Note:** ECMA-262 defines a `block` as a list of statements. A function declartion is not a statement. [Read ECMA-262's note on this issue](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf#page=97).\r\n\r\n ```javascript\r\n // bad\r\n if (currentUser) {\r\n function test() {\r\n console.log('Nope.');\r\n }\r\n }\r\n\r\n // good\r\n if (currentUser) {\r\n var test = function test() {\r\n console.log('Yup.');\r\n };\r\n }\r\n ```\r\n\r\n - Never name a parameter `arguments`, this will take precedence over the `arguments` object that is given to every function scope.\r\n\r\n ```javascript\r\n // bad\r\n function nope(name, options, arguments) {\r\n // ...stuff...\r\n }\r\n\r\n // good\r\n function yup(name, options, args) {\r\n // ...stuff...\r\n }\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n\r\n## <a name='properties'>Properties</a>\r\n\r\n - Use dot notation when accessing properties.\r\n\r\n ```javascript\r\n var luke = {\r\n jedi: true,\r\n age: 28\r\n };\r\n\r\n // bad\r\n var isJedi = luke['jedi'];\r\n\r\n // good\r\n var isJedi = luke.jedi;\r\n ```\r\n\r\n - Use subscript notation `[]` when accessing properties with a variable.\r\n\r\n ```javascript\r\n var luke = {\r\n jedi: true,\r\n age: 28\r\n };\r\n\r\n function getProp(prop) {\r\n return luke[prop];\r\n }\r\n\r\n var isJedi = getProp('jedi');\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='variables'>Variables</a>\r\n\r\n - 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.\r\n\r\n ```javascript\r\n // bad\r\n superPower = new SuperPower();\r\n\r\n // good\r\n var superPower = new SuperPower();\r\n ```\r\n\r\n - Use one `var` declaration for multiple variables and declare each variable on a newline.\r\n\r\n ```javascript\r\n // bad\r\n var items = getItems();\r\n var goSportsTeam = true;\r\n var dragonball = 'z';\r\n\r\n // good\r\n var items = getItems(),\r\n goSportsTeam = true,\r\n dragonball = 'z';\r\n ```\r\n\r\n - 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.\r\n\r\n ```javascript\r\n // bad\r\n var i, len, dragonball,\r\n items = getItems(),\r\n goSportsTeam = true;\r\n\r\n // bad\r\n var i, items = getItems(),\r\n dragonball,\r\n goSportsTeam = true,\r\n len;\r\n\r\n // good\r\n var items = getItems(),\r\n goSportsTeam = true,\r\n dragonball,\r\n i, length;\r\n ```\r\n\r\n - Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.\r\n\r\n ```javascript\r\n // bad\r\n function() {\r\n test();\r\n console.log('doing stuff..');\r\n\r\n //..other stuff..\r\n\r\n var name = getName();\r\n\r\n if (name === 'test') {\r\n return false;\r\n }\r\n\r\n return name;\r\n }\r\n\r\n // good\r\n function() {\r\n var name = getName();\r\n\r\n test();\r\n console.log('doing stuff..');\r\n\r\n //..other stuff..\r\n\r\n if (name === 'test') {\r\n return false;\r\n }\r\n\r\n return name;\r\n }\r\n\r\n // bad\r\n function() {\r\n var name = getName();\r\n\r\n if (!arguments.length) {\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n // good\r\n function() {\r\n if (!arguments.length) {\r\n return false;\r\n }\r\n\r\n var name = getName();\r\n\r\n return true;\r\n }\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='hoisting'>Hoisting</a>\r\n\r\n - Variable declarations get hoisted to the top of their scope, their assignment does not.\r\n\r\n ```javascript\r\n // we know this wouldn't work (assuming there\r\n // is no notDefined global variable)\r\n function example() {\r\n console.log(notDefined); // => throws a ReferenceError\r\n }\r\n\r\n // creating a variable declaration after you\r\n // reference the variable will work due to\r\n // variable hoisting. Note: the assignment\r\n // value of `true` is not hoisted.\r\n function example() {\r\n console.log(declaredButNotAssigned); // => undefined\r\n var declaredButNotAssigned = true;\r\n }\r\n\r\n // The interpretor is hoisting the variable\r\n // declaration to the top of the scope.\r\n // Which means our example could be rewritten as:\r\n function example() {\r\n var declaredButNotAssigned;\r\n console.log(declaredButNotAssigned); // => undefined\r\n declaredButNotAssigned = true;\r\n }\r\n ```\r\n\r\n - Anonymous function expressions hoist their variable name, but not the function assignment.\r\n\r\n ```javascript\r\n function example() {\r\n console.log(anonymous); // => undefined\r\n\r\n anonymous(); // => TypeError anonymous is not a function\r\n\r\n var anonymous = function() {\r\n console.log('anonymous function expression');\r\n };\r\n }\r\n ```\r\n\r\n - Named function expressions hoist the variable name, not the function name or the function body.\r\n\r\n ```javascript\r\n function example() {\r\n console.log(named); // => undefined\r\n\r\n named(); // => TypeError named is not a function\r\n\r\n superPower(); // => ReferenceError superPower is not defined\r\n\r\n var named = function superPower() {\r\n console.log('Flying');\r\n };\r\n\r\n\r\n // the same is true when the function name\r\n // is the same as the variable name.\r\n function example() {\r\n console.log(named); // => undefined\r\n\r\n named(); // => TypeError named is not a function\r\n\r\n var named = function named() {\r\n console.log('named');\r\n };\r\n }\r\n }\r\n ```\r\n\r\n - Function declarations hoist their name and the function body.\r\n\r\n ```javascript\r\n function example() {\r\n superPower(); // => Flying\r\n\r\n function superPower() {\r\n console.log('Flying');\r\n }\r\n }\r\n ```\r\n\r\n - For more information refer to [JavaScript Scoping & Hoisting](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting) by [Ben Cherry](http://www.adequatelygood.com/)\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n\r\n## <a name='conditionals'>Conditional Expressions & Equality</a>\r\n\r\n - Use `===` and `!==` over `==` and `!=`.\r\n - Conditional expressions are evaluated using coercion with the `ToBoolean` method and always follow these simple rules:\r\n\r\n + **Objects** evaluate to **true**\r\n + **Undefined** evaluates to **false**\r\n + **Null** evaluates to **false**\r\n + **Booleans** evaluate to **the value of the boolean**\r\n + **Numbers** evalute to **false** if **+0, -0, or NaN**, otherwise **true**\r\n + **Strings** evaluate to **false** if an empty string `''`, otherwise **true**\r\n\r\n ```javascript\r\n if ([0]) {\r\n // true\r\n // An array is an object, objects evaluate to true\r\n }\r\n ```\r\n\r\n - Use shortcuts.\r\n\r\n ```javascript\r\n // bad\r\n if (name !== '') {\r\n // ...stuff...\r\n }\r\n\r\n // good\r\n if (name) {\r\n // ...stuff...\r\n }\r\n\r\n // bad\r\n if (collection.length > 0) {\r\n // ...stuff...\r\n }\r\n\r\n // good\r\n if (collection.length) {\r\n // ...stuff...\r\n }\r\n ```\r\n\r\n - For more information see [Truth Equality and JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='blocks'>Blocks</a>\r\n\r\n - Use braces with all multi-line blocks.\r\n\r\n ```javascript\r\n // bad\r\n if (test)\r\n return false;\r\n\r\n // good\r\n if (test) return false;\r\n\r\n // good\r\n if (test) {\r\n return false;\r\n }\r\n\r\n // bad\r\n function() { return false; }\r\n\r\n // good\r\n function() {\r\n return false;\r\n }\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='comments'>Comments</a>\r\n\r\n - Use `/** ... */` for multiline comments. Include a description, specify types and values for all parameters and return values.\r\n\r\n ```javascript\r\n // bad\r\n // make() returns a new element\r\n // based on the passed in tag name\r\n //\r\n // @param <String> tag\r\n // @return <Element> element\r\n function make(tag) {\r\n\r\n // ...stuff...\r\n\r\n return element;\r\n }\r\n\r\n // good\r\n /**\r\n * make() returns a new element\r\n * based on the passed in tag name\r\n *\r\n * @param <String> tag\r\n * @return <Element> element\r\n */\r\n function make(tag) {\r\n\r\n // ...stuff...\r\n\r\n return element;\r\n }\r\n ```\r\n\r\n - Use `//` for single line comments. Place single line comments on a newline above the subject of the comment. Put an emptyline before the comment.\r\n\r\n ```javascript\r\n // bad\r\n var active = true; // is current tab\r\n\r\n // good\r\n // is current tab\r\n var active = true;\r\n\r\n // bad\r\n function getType() {\r\n console.log('fetching type...');\r\n // set the default type to 'no type'\r\n var type = this._type || 'no type';\r\n\r\n return type;\r\n }\r\n\r\n // good\r\n function getType() {\r\n console.log('fetching type...');\r\n\r\n // set the default type to 'no type'\r\n var type = this._type || 'no type';\r\n\r\n return type;\r\n }\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='whitespace'>Whitespace</a>\r\n\r\n - Use soft tabs set to 2 spaces\r\n\r\n ```javascript\r\n // bad\r\n function() {\r\n ∙∙∙∙var name;\r\n }\r\n\r\n // bad\r\n function() {\r\n ∙var name;\r\n }\r\n\r\n // good\r\n function() {\r\n ∙∙var name;\r\n }\r\n ```\r\n - Place 1 space before the leading brace.\r\n\r\n ```javascript\r\n // bad\r\n function test(){\r\n console.log('test');\r\n }\r\n\r\n // good\r\n function test() {\r\n console.log('test');\r\n }\r\n\r\n // bad\r\n dog.set('attr',{\r\n age: '1 year',\r\n breed: 'Bernese Mountain Dog'\r\n });\r\n\r\n // good\r\n dog.set('attr', {\r\n age: '1 year',\r\n breed: 'Bernese Mountain Dog'\r\n });\r\n ```\r\n - Place an empty newline at the end of the file.\r\n\r\n ```javascript\r\n // bad\r\n (function(global) {\r\n // ...stuff...\r\n })(this);\r\n ```\r\n\r\n ```javascript\r\n // good\r\n (function(global) {\r\n // ...stuff...\r\n })(this);\r\n\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n - Use indentation when making long method chains.\r\n\r\n ```javascript\r\n // bad\r\n $('#items').find('.selected').highlight().end().find('.open').updateCount();\r\n\r\n // good\r\n $('#items')\r\n .find('.selected')\r\n .highlight()\r\n .end()\r\n .find('.open')\r\n .updateCount();\r\n\r\n // bad\r\n var leds = stage.selectAll('.led').data(data).enter().append(\"svg:svg\").class('led', true)\r\n .attr('width', (radius + margin) * 2).append(\"svg:g\")\r\n .attr(\"transform\", \"translate(\" + (radius + margin) + \",\" + (radius + margin) + \")\")\r\n .call(tron.led);\r\n\r\n // good\r\n var leds = stage.selectAll('.led')\r\n .data(data)\r\n .enter().append(\"svg:svg\")\r\n .class('led', true)\r\n .attr('width', (radius + margin) * 2)\r\n .append(\"svg:g\")\r\n .attr(\"transform\", \"translate(\" + (radius + margin) + \",\" + (radius + margin) + \")\")\r\n .call(tron.led);\r\n ```\r\n\r\n## <a name='leading-commas'>Leading Commas</a>\r\n\r\n - **Nope.**\r\n\r\n ```javascript\r\n // bad\r\n var once\r\n , upon\r\n , aTime;\r\n\r\n // good\r\n var once,\r\n upon,\r\n aTime;\r\n\r\n // bad\r\n var hero = {\r\n firstName: 'Bob'\r\n , lastName: 'Parr'\r\n , heroName: 'Mr. Incredible'\r\n , superPower: 'strength'\r\n };\r\n\r\n // good\r\n var hero = {\r\n firstName: 'Bob',\r\n lastName: 'Parr',\r\n heroName: 'Mr. Incredible',\r\n superPower: 'strength'\r\n };\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='semicolons'>Semicolons</a>\r\n\r\n - **Yup.**\r\n\r\n ```javascript\r\n // bad\r\n (function() {\r\n var name = 'Skywalker'\r\n return name\r\n })()\r\n\r\n // good\r\n (function() {\r\n var name = 'Skywalker';\r\n return name;\r\n })();\r\n\r\n // good\r\n ;(function() {\r\n var name = 'Skywalker';\r\n return name;\r\n })();\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='type-coercion'>Type Casting & Coercion</a>\r\n\r\n - Perform type coercion at the beginning of the statement.\r\n - Strings:\r\n\r\n ```javascript\r\n // => this.reviewScore = 9;\r\n\r\n // bad\r\n var totalScore = this.reviewScore + '';\r\n\r\n // good\r\n var totalScore = '' + this.reviewScore;\r\n\r\n // bad\r\n var totalScore = '' + this.reviewScore + ' total score';\r\n\r\n // good\r\n var totalScore = this.reviewScore + ' total score';\r\n ```\r\n\r\n - Use `parseInt` for Numbers and always with a radix for type casting.\r\n - 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.\r\n\r\n ```javascript\r\n var inputValue = '4';\r\n\r\n // bad\r\n var val = new Number(inputValue);\r\n\r\n // bad\r\n var val = +inputValue;\r\n\r\n // bad\r\n var val = inputValue >> 0;\r\n\r\n // bad\r\n var val = parseInt(inputValue);\r\n\r\n // good\r\n var val = Number(inputValue);\r\n\r\n // good\r\n var val = parseInt(inputValue, 10);\r\n\r\n // good\r\n /**\r\n * parseInt was the reason my code was slow.\r\n * Bitshifting the String to coerce it to a\r\n * Number made it a lot faster.\r\n */\r\n var val = inputValue >> 0;\r\n ```\r\n\r\n - Booleans:\r\n\r\n ```javascript\r\n var age = 0;\r\n\r\n // bad\r\n var hasAge = new Boolean(age);\r\n\r\n // good\r\n var hasAge = Boolean(age);\r\n\r\n // good\r\n var hasAge = !!age;\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='naming-conventions'>Naming Conventions</a>\r\n\r\n - Avoid single letter names. Be descriptive with your naming.\r\n\r\n ```javascript\r\n // bad\r\n function q() {\r\n // ...stuff...\r\n }\r\n\r\n // good\r\n function query() {\r\n // ..stuff..\r\n }\r\n ```\r\n\r\n - Use camelCase when naming objects, functions, and instances\r\n\r\n ```javascript\r\n // bad\r\n var OBJEcttsssss = {};\r\n var this_is_my_object = {};\r\n var this-is-my-object = {};\r\n function c() {};\r\n var u = new user({\r\n name: 'Bob Parr'\r\n });\r\n\r\n // good\r\n var thisIsMyObject = {};\r\n function thisIsMyFunction() {};\r\n var user = new User({\r\n name: 'Bob Parr'\r\n });\r\n ```\r\n\r\n - Use PascalCase when naming constructors or classes\r\n\r\n ```javascript\r\n // bad\r\n function user(options) {\r\n this.name = options.name;\r\n }\r\n\r\n var bad = new user({\r\n name: 'nope'\r\n });\r\n\r\n // good\r\n function User(options) {\r\n this.name = options.name;\r\n }\r\n\r\n var good = new User({\r\n name: 'yup'\r\n });\r\n ```\r\n\r\n - Use a leading underscore `_` when naming private properties\r\n\r\n ```javascript\r\n // bad\r\n this.__firstName__ = 'Panda';\r\n this.firstName_ = 'Panda';\r\n \r\n // good\r\n this._firstName = 'Panda';\r\n ```\r\n\r\n - When saving a reference to `this` use `_this`.\r\n\r\n ```javascript\r\n // bad\r\n function() {\r\n var self = this;\r\n return function() {\r\n console.log(self);\r\n };\r\n }\r\n\r\n // bad\r\n function() {\r\n var that = this;\r\n return function() {\r\n console.log(that);\r\n };\r\n }\r\n\r\n // good\r\n function() {\r\n var _this = this;\r\n return function() {\r\n console.log(_this);\r\n };\r\n }\r\n ```\r\n\r\n - Name your functions. This is helpful for stack traces.\r\n\r\n ```javascript\r\n // bad\r\n var log = function(msg) {\r\n console.log(msg);\r\n };\r\n\r\n // good\r\n var log = function log(msg) {\r\n console.log(msg);\r\n };\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='accessors'>Accessors</a>\r\n\r\n - Accessor functions for properties are not required\r\n - If you do make accessor functions use getVal() and setVal('hello')\r\n\r\n ```javascript\r\n // bad\r\n dragon.age();\r\n\r\n // good\r\n dragon.getAge();\r\n\r\n // bad\r\n dragon.age(25);\r\n\r\n // good\r\n dragon.setAge(25);\r\n ```\r\n\r\n - If the property is a boolean, use isVal() or hasVal()\r\n\r\n ```javascript\r\n // bad\r\n if (!dragon.age()) {\r\n return false;\r\n }\r\n\r\n // good\r\n if (!dragon.hasAge()) {\r\n return false;\r\n }\r\n ```\r\n\r\n - It's okay to create get() and set() functions, but be consistent.\r\n\r\n ```javascript\r\n function Jedi(options) {\r\n options || (options = {});\r\n var lightsaber = options.lightsaber || 'blue';\r\n this.set('lightsaber', lightsaber);\r\n }\r\n\r\n Jedi.prototype.set = function(key, val) {\r\n this[key] = val;\r\n };\r\n\r\n Jedi.prototype.get = function(key) {\r\n return this[key];\r\n };\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='constructors'>Constructors</a>\r\n\r\n - 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!\r\n\r\n ```javascript\r\n function Jedi() {\r\n console.log('new jedi');\r\n }\r\n\r\n // bad\r\n Jedi.prototype = {\r\n fight: function fight() {\r\n console.log('fighting');\r\n },\r\n\r\n block: function block() {\r\n console.log('blocking');\r\n }\r\n };\r\n\r\n // good\r\n Jedi.prototype.fight = function fight() {\r\n console.log('fighting');\r\n };\r\n\r\n Jedi.prototype.block = function block() {\r\n console.log('blocking');\r\n };\r\n ```\r\n\r\n - Methods can return `this` to help with method chaining.\r\n\r\n ```javascript\r\n // bad\r\n Jedi.prototype.jump = function() {\r\n this.jumping = true;\r\n return true;\r\n };\r\n\r\n Jedi.prototype.setHeight = function(height) {\r\n this.height = height;\r\n };\r\n\r\n var luke = new Jedi();\r\n luke.jump(); // => true\r\n luke.setHeight(20) // => undefined\r\n\r\n // good\r\n Jedi.prototype.jump = function() {\r\n this.jumping = true;\r\n return this;\r\n };\r\n\r\n Jedi.prototype.setHeight = function(height) {\r\n this.height = height;\r\n return this;\r\n };\r\n\r\n var luke = new Jedi();\r\n\r\n luke.jump()\r\n .setHeight(20);\r\n ```\r\n\r\n\r\n - It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.\r\n\r\n ```javascript\r\n function Jedi(options) {\r\n options || (options = {});\r\n this.name = options.name || 'no name';\r\n }\r\n\r\n Jedi.prototype.getName = function getName() {\r\n return this.name;\r\n };\r\n\r\n Jedi.prototype.toString = function toString() {\r\n return 'Jedi - ' + this.getName();\r\n };\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='modules'>Modules</a>\r\n\r\n - 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.\r\n - The file should be named with camelCase, live in a folder with the same name, and match the name of the single export.\r\n - Add a method called noConflict() that sets the exported module to the previous version and returns this one.\r\n - Always declare `'use strict';` at the top of the module.\r\n\r\n ```javascript\r\n // fancyInput/fancyInput.js\r\n\r\n !function(global) {\r\n 'use strict';\r\n\r\n var previousFancyInput = global.FancyInput;\r\n\r\n function FancyInput(options) {\r\n this.options = options || {};\r\n }\r\n\r\n FancyInput.noConflict = function noConflict() {\r\n global.FancyInput = previousFancyInput;\r\n return FancyInput;\r\n };\r\n\r\n global.FancyInput = FancyInput;\r\n }(this);\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='jquery'>jQuery</a>\r\n\r\n - Prefix jQuery object variables with a `$`.\r\n\r\n ```javascript\r\n // bad\r\n var sidebar = $('.sidebar');\r\n\r\n // good\r\n var $sidebar = $('.sidebar');\r\n ```\r\n\r\n - Cache jQuery lookups.\r\n\r\n ```javascript\r\n // bad\r\n function setSidebar() {\r\n $('.sidebar').hide();\r\n\r\n // ...stuff...\r\n\r\n $('.sidebar').css({\r\n 'background-color': 'pink'\r\n });\r\n }\r\n\r\n // good\r\n function setSidebar() {\r\n var $sidebar = $('.sidebar');\r\n $sidebar.hide();\r\n\r\n // ...stuff...\r\n\r\n $sidebar.css({\r\n 'background-color': 'pink'\r\n });\r\n }\r\n ```\r\n\r\n - For DOM queries use Cascading `$('.sidebar ul')` or parent > child `$('.sidebar > .ul')`. [jsPerf](http://jsperf.com/jquery-find-vs-context-sel/16)\r\n - Use `find` with scoped jQuery object queries.\r\n\r\n ```javascript\r\n // bad\r\n $('.sidebar', 'ul').hide();\r\n\r\n // bad\r\n $('.sidebar').find('ul').hide();\r\n\r\n // good\r\n $('.sidebar ul').hide();\r\n\r\n // good\r\n $('.sidebar > ul').hide();\r\n\r\n // good (slower)\r\n $sidebar.find('ul');\r\n\r\n // good (faster)\r\n $($sidebar[0]).find('ul');\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='es5'>ECMAScript 5 Compatibility</a>\r\n\r\n - Refer to [Kangax](https://twitter.com/kangax/)'s ES5 [compatibility table](http://kangax.github.com/es5-compat-table/)\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='testing'>Testing</a>\r\n\r\n - **Yup.**\r\n\r\n ```javascript\r\n function() {\r\n return true;\r\n }\r\n ```\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='performance'>Performance</a>\r\n\r\n - [String vs Array Concat](http://jsperf.com/string-vs-array-concat/2)\r\n - [Try/Catch Cost In a Loop](http://jsperf.com/try-catch-in-loop-cost)\r\n - [Bang Function](http://jsperf.com/bang-function)\r\n - [jQuery Find vs Context, Selector](http://jsperf.com/jquery-find-vs-context-sel/13)\r\n - [innerHTML vs textContent for script text](http://jsperf.com/innerhtml-vs-textcontent-for-script-text)\r\n - [Long String Concatenation](http://jsperf.com/ya-string-concat)\r\n - Loading...\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n\r\n## <a name='resources'>Resources</a>\r\n\r\n\r\n**Read This**\r\n\r\n - [Annotated ECMAScript 5.1](http://es5.github.com/)\r\n\r\n**Other Styleguides**\r\n\r\n - [Google JavaScript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml)\r\n - [jQuery Core Style Guidelines](http://docs.jquery.com/JQuery_Core_Style_Guidelines)\r\n - [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwldrn/idiomatic.js/)\r\n\r\n**Other Styles**\r\n\r\n - [Naming this in nested functions](https://gist.github.com/4135065) - Christian Johansen\r\n\r\n**Books**\r\n\r\n - [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) - Douglas Crockford\r\n - [JavaScript Patterns](http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752) - Stoyan Stefanov\r\n - [Pro JavaScript Design Patterns](http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X) - Ross Harmes and Dustin Diaz\r\n - [High Performance Web Sites: Essential Knowledge for Front-End Engineers](http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309) - Steve Souders\r\n - [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680) - Nicholas C. Zakas\r\n - [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X) - Alex MacCaw\r\n - [Pro JavaScript Techniques](http://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273) - John Resig\r\n - [Smashing Node.js: JavaScript Everywhere](http://www.amazon.com/Smashing-Node-js-JavaScript-Everywhere-Magazine/dp/1119962595) - Guillermo Rauch\r\n\r\n**Blogs**\r\n\r\n - [DailyJS](http://dailyjs.com/)\r\n - [JavaScript Weekly](http://javascriptweekly.com/)\r\n - [JavaScript, JavaScript...](http://javascriptweblog.wordpress.com/)\r\n - [Bocoup Weblog](http://weblog.bocoup.com/)\r\n - [Adequately Good](http://www.adequatelygood.com/)\r\n - [NCZOnline](http://www.nczonline.net/)\r\n - [Perfection Kills](http://perfectionkills.com/)\r\n - [Ben Alman](http://benalman.com/)\r\n - [Dmitry Baranovskiy](http://dmitry.baranovskiy.com/)\r\n - [Dustin Diaz](http://dustindiaz.com/)\r\n - [nettuts](http://net.tutsplus.com/?s=javascript)\r\n\r\n **[[⬆]](#TOC)**\r\n\r\n## <a name='in-the-wild'>In the Wild</a>\r\n\r\n 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.\r\n\r\n - **Airbnb**: [airbnb/javascript](//github.com/airbnb/javascript)\r\n - **American Insitutes for Research**: [AIRAST/javascript](//github.com/AIRAST/javascript)\r\n - **GoCardless**: [gocardless/javascript](//github.com/gocardless/javascript)\r\n - **GoodData**: [gooddata/gdc-js-style](//github.com/gooddata/gdc-js-style)\r\n - **How About We**: [howaboutwe/javascript](//github.com/howaboutwe/javascript)\r\n - **MinnPost**: [MinnPost/javascript](//github.com/MinnPost/javascript)\r\n - **National Geographic**: [natgeo/javascript](https://github.com/natgeo/javascript)\r\n - **Razorfish**: [razorfish/javascript-style-guide](//github.com/razorfish/javascript-style-guide)\r\n - **Shutterfly**: [shutterfly/javascript](//github.com/shutterfly/javascript)\r\n\r\n## <a name='guide-guide'>The JavaScript Style Guide Guide</a>\r\n\r\n - [Reference](//github.com/airbnb/javascript/wiki/The-JavaScript-Style-Guide-Guide)\r\n\r\n## <a name='authors'>Contributors</a>\r\n\r\n - [View Contributors](https://github.com/airbnb/javascript/graphs/contributors)\r\n\r\n\r\n## <a name='license'>License</a>\r\n\r\n(The MIT License)\r\n\r\nCopyright (c) 2012 Airbnb\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining\r\na copy of this software and associated documentation files (the\r\n'Software'), to deal in the Software without restriction, including\r\nwithout limitation the rights to use, copy, modify, merge, publish,\r\ndistribute, sublicense, and/or sell copies of the Software, and to\r\npermit persons to whom the Software is furnished to do so, subject to\r\nthe following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be\r\nincluded in all copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\r\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\r\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\r\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n**[[⬆]](#TOC)**\r\n\r\n# };\r\n\r\n","name":"Javascript","google":"","note":"Don't delete this file! It's used internally to help with page regeneration.","tagline":"JavaScript Style Guide"}