Better than anarchy!
- Objects
- Arrays
- Strings
- Functions
- Iterators
- Properties
- Variables
- Hoisting
- Comparison Operators & Equality
- Blocks
- Control Statements
- Comments
- Whitespace
- Commas
- Semicolons
- Type Casting & Coercion
- Naming Conventions
- Accessors
- Events
- Exception Handling
- lodash
- Sundries
- AngularJS
- License
-
1.1 Use the literal syntax for object creation.
no-new-object
// bad var item = new Object(); // good var item = {};
-
1.2 Only quote properties that are invalid identifiers.
quote-props
Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.
// bad var bad = { 'foo': 3, 'bar': 4, 'data-blah': 5, }; // good var good = { foo: 3, bar: 4, 'data-blah': 5, };
-
1.3 Do not call
Object.prototype
methods directly, such ashasOwnProperty
,propertyIsEnumerable
, andisPrototypeOf
.Why? These methods may be shadowed by properties on the object in question - consider
{ hasOwnProperty: false }
- or, the object may be a null object (Object.create(null)
).// bad console.log(object.hasOwnProperty(key)); // good console.log(Object.prototype.hasOwnProperty.call(object, key));
-
2.1 Use the literal syntax for array creation.
no-array-constructor
// bad var items = new Array(); // good var items = [];
-
2.2 Use Array#push instead of direct assignment to add items to an array.
var someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
-
2.3 Use line breaks after open and before close array brackets if an array has multiple lines
// bad var arr = [ [0, 1], [2, 3], [4, 5], ]; var objectInArray = [{ id: 1, }, { id: 2, }]; var numberInArray = [ 1, 2, ]; // good var arr = [[0, 1], [2, 3], [4, 5]]; var objectInArray = [ { id: 1 }, { id: 2 } ]; var objectInArray = [ { id: 1 }, { id: 2 } ]; var numberInArray = [ 1, 2 ];
-
3.1 Use single quotes
'
for strings. (quotes
)// bad var name = "Buckaroo Banzai"; var note = "Doesn't play accordion. Likes \"The Sound of Music\"."; // good var name = 'Buckaroo Banzai'; var note = 'Doesn\'t play accordion. Likes "The Sound of Music".';
-
3.2 Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation.
max-len
has an option to allow ignoring strings that exceed the line limitWhy? Broken strings are painful to work with and make code less searchable.
// 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.';
-
3.4 Do not unnecessarily escape characters in strings.
no-useless-escape
Why? Backslashes harm readability, thus they should only be present when necessary.
// bad var foo = '\'this\' \i\s \"quoted\"'; // good var foo = '\'this\' is "quoted"';
-
3.5 Do not use
new String
, use literals instead.no-new-wrappers
// bad var myString = new String; var hisString = new String(); var herString = new String(''); // good var everyonesString = '';
-
4.1 Use named function expressions instead of function declarations.
func-style
Why? Function declarations are hoisted, which means that it’s easy - too easy - to reference the function before it is defined in the file. This harms readability and maintainability. If you find that a function’s definition is large or complex enough that it is interfering with understanding the rest of the file, then perhaps it’s time to extract it to its own module! Don’t forget to name the expression - anonymous functions can make it harder to locate the problem in an Error’s call stack.
// bad function foo() { // ... } // bad var foo = function () { // ... }; // bad var foo = function bar() { // ... }; // good var foo = function foo() { // ... };
-
4.2 Wrap immediately invoked function expressions in parentheses.
wrap-iife
Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this.
// immediately-invoked function expression (IIFE) (function () { console.log('Welcome to the Internet. Please follow me.'); }());
- 4.3 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.no-loop-func
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.
-
4.4 Never name a parameter
arguments
. This will take precedence over thearguments
object that is given to every function scope.// bad function foo(name, options, arguments) { // ... } // good function foo(name, options, args) { // ... }
-
4.5 Never use the Function constructor to create a new function.
no-new-func
Why? Creating a function in this way evaluates a string similarly to eval(), which opens vulnerabilities.
// bad var add = new Function('a', 'b', 'return a + b'); // still bad var subtract = Function('a', 'b', 'return a - b');
-
4.6 Provide spaces between 1) the
function
keyword and the parens for anonymous functions and 2) the close-paren and opening brace.space-before-function-paren
space-before-blocks
Why? You shouldn’t have to add or remove a space when adding or removing a name.
// bad var f = function(){ // ... }; var g = function (){ // ... }; foo( function(){ // ... } ); // good var f = function f() { // ... }; var g = function g() { // ... }; foo( function () { // ... } );
-
4.7 Mutate parameters only at the top of the function, in a parameter-processing/early-return block. (Unless the funtion exists solely to mutate the input parameters)
From experience in other languages, notably pure functional ones, many coders have a reasonable expectation that input parameters will remain unchanged throughout the code body. We use the common idiom of checking and processing parameters (e.g. setting defaults) as an inital block for the function. Avoid mutation after such processing because it violates expectations.
// bad function f(p) { // lots of code p = 7; // lots more code } // good function f(p) { p = p || 'default'; // meat of function }
-
4.8 Never reassign parameters.
no-param-reassign
Why? It's confusing. Reviewers expect possible mutation of parameters, but not complete reassignment. Reassigning parameters can also lead to unexpected behavior, especially when accessing the
arguments
object. And can cause optimization issues, especially in V8.// bad function f1(a) { a = 1; // ... } function f2(a) { if (!a) { a = 1; } // ... } // good function f3(a) { var b = a || 1; // ... }
-
4.9 Functions with multiline signatures, or invocations, should be indented just like every other multiline list in this guide: with each item on a line by itself.
// bad function foo(bar, baz, quux) { // ... } // good function foo(bar, baz, quux) {}; function foo( bar, baz, quux ) { // ... } // bad console.log(foo, bar, baz); // good console.log(foo, bar, baz, quux); console.log( foo, bar, baz );
-
4.10 Avoid boolean parameters.
Why? While boolean parameters convey their meaning clearly within the function definition, they do not at the sites of the calls. Use hashes with named parameters to convey their purpose in the context from which they are called.
// bad var fall = function fall(object, up) { var g = ACCELERATION_FROM_EARTH; if (up) { g = -g; } // handle falling } fall(object, true); // good var fall = function fall(object, options) { var g = UNIVERSAL_CONSTANTS.accelerationDueToEarthsGravity; if (options.direction === 'up') { g = -g; } // handle falling } fall(object, { direction: 'up' }); // bad (real code) initMouseEvent( eventType, true /* bubble */, true /* cancelable */, window, null, 0, 0, 0, 0, /* coordinates */ false, false, false, false, /* modifier keys */ 0 /*left*/, null ); // so much better initMouseEvent({ eventType: eventType, bubble: true, cancelable: true }); // worse, but ok initMouseEvent({ eventType: eventType, bubble: true, cancelable: true, coordinates: [0, 0, 0, 0], modifierKeys: { shift: false, control: false, alt: false, command: false }, leftButton: false, whoKnows: null });
-
4.11 Add spaces between function parameters of the outermost function.
// bad foo(a,b,c); bar(baz(a,1),baz(b,2),baz(c,3)); // good foo(a, b, c); bar(baz(a,1), baz(b,2), baz(c,3));
-
4.12 Isolate all function definitions to their own lines.
// bad var largeNumbers = numbers.filter(function (val) { return val >= 100; }); // good var largeNumbers = numbers.filter( function (val) { return val >= 100; } ); // bad return Customer .get(cid) .then(function (customer) { customer.processed = true; return customer; }); // good return Customer .get(cid) .then( function (customer) { customer.processed = true; return customer; } ); // bad var interface = { foo: function () { return 'foo'; }, bar: function () { return 'bar'; } }; // good var interface = { foo: function () { return 'foo'; }, bar: function () { return 'bar'; } };
-
5.1 Don’t use
for
iterators. Prefer JavaScript’s higher-order functions instead of loops likefor-in
orfor-of
. (If you have to do an early return, there may be no good way around it though.)no-iterator
no-restricted-syntax
Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
Use
map()
/every()
/filter()
/find()
/findIndex()
/reduce()
/some()
/ ... to iterate over arrays, andObject.keys()
/Object.values()
/Object.entries()
to produce arrays so you can iterate over objects. Use lodash liberally and without hesitation (underscore is also good, but we recommend lodash for consistency).var numbers = [1, 2, 3, 4, 5]; // bad var sum = 0; for (var num of numbers) { sum += num; } sum === 15; // good var sum = 0; numbers.forEach( function (num) { sum += num; } ); sum === 15; // better (use the functional force) var sum = numbers.reduce( function(total, num) { return total + num; }, 0 ); sum === 15; // best (lodash) var sum = _.reduce( numbers, function(total, num) { return total + num; }, 0 ); // bad var increasedByOne = []; for(var i = 0; i < numbers.length; i++) { increasedByOne.push(numbers[i] + 1); } // good var increasedByOne = []; numbers.forEach( function (num) { increasedByOne.push(num + 1); } ); // better (keeping it functional) var increasedByOne = numbers.map( function (num) { return num + 1; } ); // best (lodash) var increasedByOne = _.map( numbers, function (num) { return num + 1; } ); // bad function containsThree(insanelyLongArray) { var hasAThree = false; insanelyLongArray.forEach( function (value) { if (value === 3) { hasAThree = true; } } ); return hasAThree; } // good function containsThree(insanelyLongArray) { for (var i = 0; i < insanelyLongArray.length; i++) { if (insanelyLongArray[i] === 3) { return true; } return false; } // better (lodash) function containsThree(insanelyLongArray) { return _.includes( insanelyLongArray, 3 ); } // best (lodash - allow for complex conditionals) function containsThree(insanelyLongArray) { return _.some( insanelyLongArray, function (item) { return item.value === 3; } ); }
-
6.1 Use dot notation when accessing properties.
dot-notation
var luke = { jedi: true, age: 28, }; // bad var isJedi = luke['jedi']; // good var isJedi = luke.jedi;
-
6.2 Use bracket notation
[]
when accessing properties with a variable.var luke = { jedi: true, age: 28, }; function getProp(prop) { return luke[prop]; } var isJedi = getProp('jedi');
-
7.1 Always use
var
to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace.no-undef
prefer-const
// bad superPower = new SuperPower(); // good var superPower = new SuperPower();
-
7.2 Always initialize variables. If their value is unknown at the point of declaration, use
null
. Never useundefined
.init-declarations
,no-undefined
,no-undef-init
// bad var i; var foo; i = 8; var whoKnows = undefined; if (foo === undefined) {} // good var i = 8; var foo = null; var whoKnows = null; if (typeof foo === 'undefined') {}
-
7.3 Use one
var
declaration per variable.one-var
Why? It’s easier to add new variable declarations this way, and you never have to worry about swapping out a
;
for a,
or introducing punctuation-only diffs. You can also step through each declaration with the debugger, instead of jumping through all of them at once.// bad var items = getItems(), goSportsTeam = true, dragonball = 'z'; // bad // (compare to above, and try to spot the mistake) var items = getItems(), goSportsTeam = true; dragonball = 'z'; // good var items = getItems(); var goSportsTeam = true; var dragonball = 'z';
-
7.4 Capitalize your constants with SCREAMING_SNAKE_CASE.
// bad var maxNameLength = 16; var userCount = getUsers().length; // good var MAX_NAME_LENGTH = 16; var USER_COUNT = getUsers().length;
-
7.5 Group all your constants and then group all your vars. Prefer inserting a line between the two blocks. Also prefer inserting a line after these blocks to separate them from your function's actual code.
Why? This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
// very bad var i, len, dragonball, items = getItems(), goSportsTeam = true; doSomethingWith(items); // bad var i = null; var ITEMS = getItems(); var dragonball = null; var GO_SPORTS_TEAM = true; var len = null; doSomethingWith(ITEMS); // good var GO_SPORTS_TEAM = true; var ITEMS = getItems(); var dragonball = null; var i = null; var length = null; doSomethingWith(ITEMS);
-
7.6 Don’t chain variable assignments.
no-multi-assign
Why? Chaining variable assignments creates implicit global variables.
// bad function example() { // JavaScript interprets this as // var a = ( b = ( c = 1 ) ); // The var keyword only applies to variable a; variables b and c become // global variables. var a = b = c = 1; // function body... } console.log(a); // throws ReferenceError console.log(b); // 1 console.log(c); // 1 // good function example() { var a = 1; var b = a; var c = a; // function body... } console.log(a); // throws ReferenceError console.log(b); // throws ReferenceError console.log(c); // throws ReferenceError
-
7.7 Avoid using unary increments and decrements (++, --).
no-plusplus
Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like
num += 1
instead ofnum++
ornum ++
. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.// bad var array = [1, 2, 3]; var num = 1; num++; --num; var sum = 0; var truthyCount = 0; for (var i = 0; i < array.length; i++) { var value = array[i]; sum += value; if (value) { truthyCount++; } } // good var array = [1, 2, 3]; var num = 1; num += 1; num -= 1; var sum = array.reduce( function (a, b) { return a + b; }, 0 ); var truthyCount = array.filter(Boolean).length; // better (lodash) var array = [1, 2, 3]; var sum = _.reduce( array, function (a, b) { return a + b; }, 0 ); var truthyCount = _.filter(array, Boolean).length; // best (lodash - in the contrived sum case) var sum = _.sum(array);
-
7.8 Avoid abbreviations. Code is read a lot more times than it's written. Prefer full words to help convey their meaning, but keep the utility of extremely common abbreviations.
// bad var adjRnAvg = 12.8; try {} catch(ex); // good var adjustedRainfallAverage = 12.8; try {} catch(exception); // bad var loopIndexCounter = 0; var cancelButtonHyperTextMarkupLanguage = '...'; // good var i = 0; var cancelButtonHtml = '...';
-
8.1
var
declarations get hoisted to the top of their scope, but their assignment does not. Declare all variables before their first use.no-use-before-define
// 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; }
Declare all variables before their first use:
// bad function foo(wombats, marmosets) { console.log('Total: ' + wombatCount + marmosetCount); var wombatCount = wombats.length; console.log('Wombats: ' + wombatCount); var marmosetCount = marmosets.length; console.log('Marmosets count: ' + marmosetCount); } // good function foo(wombats, marmosets) { var wombatCount = wombats.length; var marmosetCount = marmosets.length; console.log('Total: ' + wombatCount + marmosetCount); console.log('Wombats: ' + wombatCount); console.log('Marmosets count: ' + marmosetCount); } // also good function foo(wombats, marmosets) { var wombatCount = wombats.length; console.log('Wombats: ' + wombatCount); var marmosetCount = marmosets.length; console.log('Marmosets count: ' + marmosetCount); console.log('Total: ' + wombatCount + marmosetCount); }
-
8.2 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'); }; }
-
8.3 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'); }; }
-
8.4 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.
-
9.2 Conditional statements such as the
if
statement evaluate their expression using coercion with theToBoolean
abstract 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 (even an empty one) is an object, objects will evaluate to true }
-
9.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers.
// bad if (isValid === true) { // ... } // good if (isValid) { // ... } // bad if (name) { // ... } // good if (name !== '') { // ... } // bad if (collection.length) { // ... } // good if (collection.length > 0) { // ... }
- 9.4 For more information see Truth Equality and JavaScript by Angus Croll.
-
9.5 Ternaries should not be nested and generally be single line expressions.
no-nested-ternary
// bad var foo = maybe1 > maybe2 ? 'bar' : value1 > value2 ? 'baz' : null; // split into 2 separated ternary expressions var maybeNull = value1 > value2 ? 'baz' : null; // better var foo = maybe1 > maybe2 ? 'bar' : maybeNull; // best var foo = maybe1 > maybe2 ? 'bar' : maybeNull;
-
9.6 Avoid unneeded ternary statements.
no-unneeded-ternary
// bad var foo = a ? a : b; var bar = c ? true : false; var baz = c ? false : true; // good var foo = a || b; var bar = !!c; var baz = !c;
-
10.1 Do not put multiple statements on the same line, debugging is easier with one statement per line.
max-statements-per-line
// bad if (test) { return false; } // good if (test) { return false; } // bad var bar = function bar() { return false; } // good var bar = function bar() { return false; }
-
10.2 Use braces with all blocks.
curly
// bad if (test) return false; // good if (test) { return false; }
-
10.3 Bracing style: use Stroustrup.
brace-style
Why? This keeps our control blocks horizontally aligned without too much extra vertical spacing, much like Python.
// bad (K&R, one true brace style) if (test) { thing1(); } else { thing2(); } // bad (Allman) if (test) { thing1(); } else { thing2(); } // good (Stroustrop) if (test) { thing1(); } else { thing3(); }
-
11.1 In case your control statement (
if
,while
etc.) gets too long or exceeds the maximum line length, each (grouped) condition should be put into a new line. The logical operator should begin the line.// bad if (foo === 123 && bar === 'abc') { thing1(); } if (foo === 123 && bar === 'abc') { thing1(); } if ((foo === 123 || bar === 'abc' || baz === 'quux') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening() && (ohno === 'it' || justKeeps === 'going')) { thing1(); } // good if (foo === 123 && bar === 'abc') { thing1(); } if ( foo === 123 && bar === 'abc' ) { thing1(); } if ( ( foo === 123 || bar === 'abc' || baz === 'quux' ) && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening() && (ohno === 'it' || justKeeps === 'going') ) { thing1(); }
-
12.1 Use
/** ... */
for multi-line comments.multiline-comment-style
// bad // make() returns a new element // based on the passed in tag name // // @param {String} tag // @returns {Element} element function make(tag) { // ... return element; } /* Adam Had 'em */ // good /** * make() returns a new element * based on the tag name * * @param {String} tag * @returns {Element} element */ function make(tag) { // ... return element; } /** * Adam * Had 'em */
-
12.2 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 unless it’s on the first line of a block.// 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; } // also good function getType() { // set the default type to 'no type' var type = this.type || 'no type'; return type; }
-
12.3 Start all comments with a space to make it easier to read.
spaced-comment
,spaced-line-comment
// bad //is current tab var active = true; // good // is current tab var active = true; // bad /** *make() returns a new element *based on the passed-in tag name */ function make(tag) { // ... return element; } // good /** * make() returns a new element * based on the passed-in tag name */ function make(tag) { // ... return element; }
- 12.4 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
.
-
12.5 Use
// FIXME:
to annotate problems.var Abacus { constructor: function constructor() { super(); // FIXME: shouldn’t use a global here total = 0; } };
-
12.6 Use
// TODO:
to annotate solutions to problems.var Abacus { constructor: function constructor() { super(); // TODO: total should be configurable by an options param this.total = 0; } }
-
12.7 Don't make unhelpful or obvious comments.
// bad // increments variable i by one i++; // Sets the number of tentacles on the monster to five for now Monster.setNumberOfTentacles(3); // Moved this here after the miso soup incident Xrvrrzhhkrrkngng.$$(false, 0, null, true, 'FALSE', undefined, { causeSystemFailures: 700.0 } ); // good i++; Monster.setNumberOfTentacles(3); /** * This call invalidates the Procyon node cache. * The string of params are all harmless defaults except the last, * which has to be a floating point, and sets failure generation to * the minimum of 700. */ Xrvrrzhhkrrkngng.$$(false, 0, null, true, 'FALSE', undefined, { causeSystemFailures: 700.0 } );
-
13.1 Use 4 spaces instead of tabs.
indent
// bad function foo() { var name; } function foo() { ∙∙var name; } // very bad function bar() { ∙var name; } function baz() { ∙∙∙∙∙∙∙∙var name; } // go away, ptr function bar() { ∙∙∙var name; } // good function baz() { ∙∙∙∙var name; }
-
13.2 Place 1 space before the leading brace.
space-before-blocks
// bad function test(){ console.log('test'); } function() {} // good function test() { console.log('test'); } function () {} // bad dog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog', }); // good dog.set('attr', { age: '1 year', breed: 'Bernese Mountain Dog', });
-
13.3 Do not place a space after the opening parenthesis in control statements (
if
,while
etc.). Place no space between the argument list and the function name in function calls and declarations.keyword-spacing
// bad if(isJedi) { run(); } else{ fight(); } // good if (isJedi) { run(); } else { fight(); } // bad while(true) {} // good while (true) {}
-
13.4 Do not place a space between the function name and the opening parenthesis when calling a function. eslint:
func-call-spacing
// bad levitate (['rocks', 'R2-D2']); // good levitate(['X-wing']);
-
13.5 Set off operators with spaces.
space-infix-ops
// bad var x=y+5; // good var x = y + 5;
-
13.6 End files with a single newline character.
eol-last
Why? Do you even POSIX? Many *nix utilities that process text files rely on all lines ending with a line break.
// bad function foo() { // ... }
// bad function foo() { // ... } ↵
// good function foo() { // ... }↵
-
13.7 When chaining calls, put each chained method on a separate line.
newline-per-chained-call
no-whitespace-before-property
// bad Customer.get(customerId).munge(customer); // good Customer .get(customerId) .munge(customer); // bad var myMungedCustomer = Customer .get(customerId) .munge(customer); var myMungedCustomer = Customer.get(customerId) .munge(customer); var myMungedCustomer = Customer.get(customerId).munge(customer); // good var myMungedCustomer = Customer .getList(customerId) .munge(customer); // bad var foo = function foo(cid) { return Customer .get(cid) .munge(); }; // good var foo = function foo(cid) { return Customer .get(cid) .munge(); }; // bad $('#items').find('.selected').highlight().end().find('.open').updateCount(); // good $('#items') .find('.selected') .highlight() .end() .find('.open') .updateCount();
-
13.8 Leave a blank line after blocks and before the next statement.
// bad if (foo) { return bar; } return baz; // good if (foo) { return bar; } return baz; // bad var arr = [ function foo() { }, function bar() { } ]; return arr; // good var arr = [ function foo() { }, function bar() { } ]; return arr;
-
13.9 Do not pad your blocks with blank lines.
padded-blocks
// bad function bar() { console.log(foo); } // bad if (baz) { console.log(qux); } else { console.log(foo); } // good if (baz) { console.log(qux); } else { console.log(foo); }
-
13.10 Don't add spaces inside parentheses function calls.
space-in-parens
Why not? It doesn't gel with the vast corpus of extant JavaScript code and seems jarring because of that.
// bad function bar( foo ) { return foo; } // good function bar(foo) { return foo; } // bad foo( bar( baz( 5 ) ) ) ); // good foo(bar(baz(5))));
-
13.11 Do not add spaces inside brackets for one-line array declarations.
array-bracket-spacing
// bad var foo = [ 1, 2, 3 ]; console.log(foo[ 0 ]) ; // good var foo = [1, 2, 3]; console.log(foo[0]);
-
13.12 Add spaces inside curly braces.
object-curly-spacing
// bad var foo = {clark: 'kent'}; // good var foo = { clark: 'kent' };
-
13.13 Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per above, long strings are exempt from this rule, and should not be broken up.
max-len
Why? This ensures readability and maintainability.
// bad var foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy; // bad $.ajax({ method: 'POST', url: 'https://fivestars.com/', data: { name: 'John' } }).done(function() { console.log('Congratulations!');}).fail(function(){console.log('You have failed this city.')}); // good var foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy; // good $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' }, }) .done( function () { console.log('Congratulations!'); } ) .fail( function () { console.log('You have failed this city.'); } ); // also acceptable $ .ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' }, }) .done( function () { console.log('Congratulations!'); } ) .fail( function () { console.log('You have failed this city.'); } );
-
14.1 Leading commas: Nope.
comma-style
// bad var story = [ once , upon , aTime ]; // good var story = [ once, upon, aTime ]; // bad var hero = { firstName: 'Ada' , lastName: 'Lovelace' , birthYear: 1815 , superPower: 'computers' , }; // good var hero = { firstName: 'Ada', lastName: 'Lovelace', birthYear: 1815, superPower: 'computers' };
-
14.2 Additional trailing comma: Nope.
comma-dangle
// bad var hero = { firstName: 'Dana', lastName: 'Scully', }; var heroes = [ 'Batman', 'Superman', ]; // good var hero = { firstName: 'Dana', lastName: 'Scully' }; var heroes = [ 'Batman', 'Superman' ]; // bad function createHero( firstName, lastName, inventorOf, ) { // does nothing } // good function createHero( firstName, lastName, inventorOf ) { // does nothing }
-
15.1 Yup. And no spaces before the semi-colon.
semi
// bad function foo() { var name = 'Skywalker' var hairstyle = "70s" ; return name } // good function foo() { var name = 'Skywalker'; var hairstyle = "70s"; return name; }
-
15.2 No spaces before the semi-colon.
semi-spacing
// bad function foo() { var name = 'Skywalker' ; return name } // good function foo() { var name = 'Skywalker'; return name; }
-
15.3 No extra semi-colons.
no-extra-semi
// bad function foo() { var name = 'Skywalker';;;;;;;; return name } // good function foo() { var name = 'Skywalker'; return name; }
- 16.1 Perform type coercion at the beginning of the statement.
-
16.2 Strings:
// bad // invokes this.reviewScore.valueOf() var totalScore = this.reviewScore + ''; // isn’t guaranteed to return a string var totalScore = this.reviewScore.toString(); // good var totalScore = String(this.reviewScore);
-
16.3 Numbers: Use
Number
for type casting andparseInt
always with a radix for parsing strings.radix
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) ; // good var val = parseInt(inputValue, 10);
-
16.4 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.// 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;
-
16.5 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:
2147483647 >> 0; // => 2147483647 2147483648 >> 0; // => -2147483648 2147483649 >> 0; // => -2147483647
-
16.6 Booleans:
var age = 0; // bad var hasAge = new Boolean(age); // good var hasAge = Boolean(age); // ok var hasAge = !!age;
-
17.1 Avoid single letter names. Be descriptive with your naming.
id-length
// bad function q() { // ... } // good function query() { // ... }
-
17.2 Use camelCase when naming objects, functions, and instances.
camelcase
// bad var OBJEcttsssss = {}; var this_is_my_object = {}; // good var thisIsMyObject = {}; function thisIsMyFunction() {}
-
17.3 Use PascalCase only when naming constructors or classes.
new-cap
// bad function funkyUser(options) { this.name = options.name; } var bad = new funkyUser({ name: 'nope', }); // good var good = new FunkyUser({ name: 'yup', });
-
17.4 Acronyms and initialisms should always be camel-cased, or all lowercased.
// bad var userID; var SMSContainer; var HTTPRequests = []; var AWSSQSQueueACKOK = what('?'); // good var userId; var smsContainer; var httpRequests = []; var AwsSqsQueueAckOk = oh('.');
- 18.1 Accessor functions for properties are not required.
-
18.2 If the property/method is a
boolean
, useisVal()
.// bad if (dragon.dead()) { return false; } // good if (dragon.isDead()) { return false; }
-
19.1 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:
// bad $(this).trigger('listingUpdated', listing.id); // ... $(this).on( 'listingUpdated', function(e, listingId) { // do something with listingId } );
prefer:
// good $(this).trigger('listingUpdated', { listingId: listing.id }); // ... $(this).on( 'listingUpdated', function(e, data) { // do something with data.listingId } );
-
20.1 For Promises, always use a
catch
call instead of passing a failure-handling function.Why? Check out this good treatment on StackOverflow
// bad foo .munge() .then( function () { // blah }, function (rejection) { // handle rejection } ); // good foo .munge() .then( function () { // blah } ) .catch( function (rejection) { // handle rejection } );
- 21.1 Use lodash liberally. Prefer lodash collection operations over JavaScript native, as they are the same for arrays and objects. Also, prefer lodash type checking functions:
isUndefined
,isNumber
, etc.
- 22.1 ESLint checks included without further comment. The links go into further detail.
block-scoped-var
block-spacing
dot-location
no-alert
no-caller
no-compare-neg-zero
no-cond-assign
no-console
no-debugger
no-dupe-args
no-dupe-keys
no-duplicate-case
no-empty
no-ex-assign
no-extra-boolean-cast
no-fallthrough
no-floating-decimal
no-func-assign
no-implicit-coercion
no-implied-eval
no-inner-declarations
no-invalid-regexp
no-invalid-this
no-irregular-whitespace
no-multi-str
no-octal
no-redeclare
no-regex-spaces
no-return-assign
no-self-assign
no-self-compare
no-throw-literal
no-trailing-spaces
no-unexpected-multiline
no-unreachable
no-unsafe-finally
no-unsafe-negation
no-unused-expressions
no-unused-vars
no-use-before-define
no-useless-call
no-useless-concat
no-useless-return
use-isnan
valid-typeof
yoda
-
23.1 Use the following structure for RequireJs and AngularJs boilerplate.
Why? We make an exception to our strict indentation style in order to conserve horizontal whitespace in the body of a module.
// bad define(['lodash', 'angular', 'uuid'], function (_, angular, uuid) { 'use strict'; return angular.module('fs-core.services.eventTracker', ['fs-core']) .service('EventTracker', [ '$window', '$log', 'Config', function EventTracker( $window, $log, Config ) { var _this = this; // ... } ]); } ); // good define([ 'lodash', 'angular', 'uuid' ], function ( _, angular, uuid ) { 'use strict'; return angular.module('fs-core.services.eventTracker', ['fs-core']) .service('EventTracker', [ '$window', '$log', 'Config', function EventTracker( $window, $log, Config ) { var _this = this; // ... } ]); } );
-
23.2 Alphabetize dependencies by variable name (not dependency string), with all
$
names earlier in the list.// bad define([ 'angular', 'crypto-js/sha1', 'fs-utils', 'machina', 'moment', 'lodash' ], function ( angular, sha1, Utils, machina, moment, _ ) { 'use strict'; // ... // good define([ 'lodash', 'angular', 'fs-utils', 'machina', 'moment', 'crypto-js/sha1' ], function ( _, angular, fsUtils, machina, moment, sha1 ) { 'use strict'; // ... // bad return angular.module('fs-core.services.customer', ['fs-core']) .service('Customer', [ 'BugReporter', 'EventTracker', 'Features', '$q', '$rootScope', 'Unified', function Customer( BugReporter, EventTracker, Features, $q, $rootScope, Unified ) { // good return angular.module('fs-core.services.customer', ['fs-core']) .service('Customer', [ '$q', '$rootScope', 'BugReporter', 'EventTracker', 'Features', 'Unified', function Customer( $q, $rootScope, BugReporter, EventTracker, Features, Unified ) {
-
23.3 Name the module function.
Why? This allows us to use
this
in the module definition (where appropriate) without style checks failing.// bad return angular.module('fs-core.services.brightness', ['fs-core']) .service('Brightness', [ '$log', '$window', 'Substrate', function ( $log, $window, Substrate ) { // good return angular.module('fs-core.services.brightness', ['fs-core']) .service('Brightness', [ '$log', '$window', 'Substrate', function Brightness( $log, $window, Substrate ) {
-
23.4 Define and use
_this
in your module constructor functionWhy? This eliminates the confusion around
this
usage in internal calls and inner functional loops. This can be especially useful in Controller implementations, where angular tries to be clever and assignthis
to the current$scope
value.// bad function FancyControl( $scope, $timeout ) { $scope.$on( '$ionicView.enter', function () { $timeout(this._putOnFancyPants, 1000); } ); this._putOnFancyPants = function _putOnFancyPants() { this._doSomething(); }; } // good function FancyControl( $scope, $timeout ) { var _this = this; $scope.$on( '$ionicView.enter', function () { $timeout(_this._putOnFancyPants, 1000); } ); this._putOnFancyPants = function _putOnFancyPants() { _this._doSomething(); }; }
-
23.5 Do not define "hidden" methods in your module closure. Prefix their name with an
_
and expose them by attaching them to_this
or whatever manner is appropriate for your module. If using_this
, be sure to invoke them from_this
when making internal calls.Why? This allows us to unit test all of our code, not just the public API.
// bad function Kitchen( Costco ) { var makeSecretSauce = function makeSecretSauce(recipe) { var ingredients = Costco.orderIngredients(recipe); var preparedSauce = mix(ingredients); return heat(preparedSauce, { source: 'sunlight', duration: '1 day' }); }; var mix = function mix() { // ... }; var heat = function heat(config) { // ... }; } // good function Kitchen( Costco ) { var _this = this; this._makeSecretSauce = function _makeSecretSauce(recipe) { var ingredients = Costco.orderIngredients(recipe); var preparedSauce = _this._mix(ingredients); return _this._heat(preparedSauce, { source: 'sunlight', duration: '1 day' }); }; this._mix = function _mix() { // ... }; this._heat = function _heat(config) { // ... }; }
-
23.6 Prefer this organization of controller componennts.
var
declarationsvar fsm = {...}
definition as final var (if applicable)$scope.$on('$ionicView.*')
lifecycle event definitionspublic
$scope
methods exposed to the view"private"
$scope._*
methods exposed for unit tests// good function RewardsControl( $filter, $scope, $timeout, Customer, Rewards ) { var _this = this; var selectedRewards = {}; $scope.$on( '$ionicView.enter', function () { selectedRewards = {}; $scope.redeemableRewards = this._getRedeemableRewards(Customer.getPoints()); } ); $scope.$on( '$ionicView.leave', function () { // ... } ); $scope.hasRedeemableRewards = function hasRedeemableRewards() { return $scope.redeemableRewards.length > 0; }; $scope.next = function next(timeout) { // ... }; $scope.back = function back() { // ... }; this._getRedeemableRewards = function _getRedeemableRewards(totalPoints) { return _.filter( Rewards.getRewards(), function (reward) { return reward.point_cost <= totalPoints; } ); }; }
(The MIT License)
Copyright (c) 2014-2017 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.