Adapted from the Airbnb JavaScript Style Guide.
- Objects
- Arrays
- Strings
- Functions
- Properties
- Variables
- Hoisting
- Conditional Expressions & Equality
- Blocks
- Comments
- Whitespace
- Commas & Semicolons
- Type Casting & Coercion
- Naming Conventions
- Modules
- jQuery
- AngularJS
- Testing
-
Use the literal syntax for object creation.
// bad var item = new Object(); // good var item = {};
-
Don't use reserved words as keys. Use readable synonyms instead.
// bad var superman = { default: { clark: 'kent' }, class: 'alien' }; // good var superman = { defaults: { clark: 'kent' }, type: 'alien' };
-
Use the literal syntax for array creation
// bad var items = new Array(); // good var items = [];
-
If you don't know array length use Array#push.
var someStack = []; // bad someStack[someStack.length] = 'abracadabra'; // good someStack.push('abracadabra');
-
When you need to copy an array use Array#slice. jsPerf
var len = items.length, itemsCopy = [], i; // bad for (i = 0; i < len; i++) { itemsCopy[i] = items[i]; } // good itemsCopy = items.slice();
-
To convert an array-like object to an array, use Array#slice.
function trigger() { var args = Array.prototype.slice.call(arguments); ... }
-
Use single quotes
''
for strings// bad var name = "Bob"; // good var name = 'Bob';
-
Strings longer than 140 characters should be written across multiple lines using string concatenation.
// 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.'); })();
-
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.
// bad if (currentUser) { function test() { console.log('Nope.'); } } // good var test; if (currentUser) { test = function test() { console.log('Yup.'); }; }
-
Never name a parameter
arguments
, this will take precedence over thearguments
object that is given to every function scope.// bad function nope(name, options, arguments) { // ...stuff... } // good function yup(name, options, args) { // ...stuff... }
-
Use dot notation when accessing properties.
var luke = { jedi: true }; // bad var isJedi = luke['jedi']; // good var isJedi = luke.jedi;
-
Use subscript notation
[]
when accessing properties with a variable.var luke = { jedi: true }; 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.// bad superPower = 'Strength'; // good var superPower = 'Strength';
-
Use one
var
declaration for multiple variables and declare each variable on a new line, indented by one tab.// bad var items = getItems(); var goSportsTeam = true; // good var items = getItems(), goSportsTeam = true;
-
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;
-
Assign variables at the top of their scope. 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; test(); console.log('doing stuff..'); //..other stuff.. name = getName(); if (name === 'test') { return false; } return name; }
-
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; }
-
Function declarations hoist their name and the function body.
function example() { superPower(); // => Flying function superPower() { console.log('Flying'); } }
-
Use
===
and!==
instead of==
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
-
Use shortcuts.
// bad if (name !== '') { // ...stuff... } // good if (name) { // ...stuff... } // bad if (collection.length > 0) { // ...stuff... } // good if (collection.length) { // ...stuff... }
-
Use braces with all blocks. Always place the opening brace on the same line as the control structure declaration with a space before it.
// bad if (test) return false; // bad if (test) return false; // good if (test) { return false; } // good for (initialization; condition; update) { statements; } // good if (someCondition) { statements; } else if (someOtherCondition) { statements; } else { statements; }
-
Use
/* ... */
for multiline comments. Include a description, specify types and values for all parameters and return values.// bad // make() returns a new element // based on the passed in tag name // // @param <String> tag // @return <Element> element function make(tag) { // ...stuff... return element; } // good /* make() returns a new element based on the passed in tag name @param <String> tag @return <Element> element */ 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;
-
If using
TODO
orFIXME
ensure that the issue is tracked somewhere other than the code as well. Address existingTODO
s orFIXME
s when you are working with code in that area.
-
Use hard tabs (set to 4 spaces)
// bad function() { ∙∙∙∙var name; } // good function() { var name; }
-
Place 1 space before the leading brace.
// 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' });
-
Surround operators with spaces.
// bad var x=y+5; // good var x = y + 5;
-
End files with a single newline character.
-
Do not leave trailing commas at the end of objects or arrays.
// bad var hero = { firstName: 'Kevin', lastName: 'Flynn', }; // bad var heroes = [ 'Batman', 'Superman', ]; // good var hero = { firstName: 'Kevin', lastName: 'Flynn' }; // good var heroes = [ 'Batman', 'Superman' ];
-
Use semicolons at the end of every statement.
-
Use
parseInt
for numbers and always with a radix for type casting.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 = parseInt(inputValue, 10);
-
Booleans:
var age = 0; // bad var hasAge = new Boolean(age); // good var hasAge = !!age;
-
Avoid single letter names unless as a local loop variable. Be descriptive with your naming.
// bad function q() { // ...stuff... } // good function query() { // ..stuff.. }
-
Use camelCase when naming objects, functions, and instances
// bad var OBJEcttsssss = {}; var this_is_my_object = {}; function c() {}; var u = new user({ name: 'Bob Parr' }); // good var thisIsMyObject = {}; function thisIsMyFunction() {}; var user = new User({ name: 'Bob Parr' });
-
Use Screaming Snake Case for constants
// bad var some_constant = 5; // good var SOME_CONSTANT = 5;
-
When saving a reference to
this
name it descriptively or use_this
.// 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); }; }
- The file should be named with camelCase, live in a folder with the same name but hyphenated, and match the name of the module in the JavaScript.
- Always declare
'use strict';
at the top of the module.
-
Prefix jQuery object variables with a
$
.// bad var sidebar = $('.sidebar'); // good var $sidebar = $('.sidebar');
-
Cache jQuery lookups.
// 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 -
Use
find
with scoped jQuery object queries.// bad $('ul', '.sidebar').hide(); // bad $('.sidebar').find('ul').hide(); // good $('.sidebar ul').hide(); // good $('.sidebar > ul').hide(); // good $sidebar.find('ul').hide();
- AngularJS should be used for new development.
- Do not mix AngularJS and JQuery. Only use one or the other in a particular feature as JQuery will cause complications with the Angular $digest cycle.
- Wrap all Angular code in an IFFE. It removes variables from the global scope and provides a variable scope for each file once all the JavaScript has been concatenated and minified.
// bad
// logger.js
var app = angular.module('app');
app.factory('logger', logger);
// logger function is added as a global variable
function logger() { }
// good
// logger.js
(function() {
'use strict';
var app = angular.module('app');
app.factory('logger', logger);
// no globals are left behind
function logger() { }
})();
- Don't use controllers for business logic, use a service or factory instead.
- Factories and services should have a single responsibility.
- DOM manipulation should occur in directives.
- Prefix directives and attributes used by directives with a short meaningful prefix (this prefix should match your CSS class prefix) to avoid naming clashes.
- Restrict directives to elements or attributes.
- All AngularJS code should have unit tests.
- 100% test code coverage is achievable with AngularJS. Use istanbul to measure code coverage.