Skip to content
This repository was archived by the owner on Apr 26, 2019. It is now read-only.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

135 Commits

Repository files navigation

HowAboutWe JavaScript Style Guide

A mostly reasonable approach to JavaScript

  1. Objects
  2. Arrays
  3. Strings
  4. Functions
  5. Properties
  6. Variables
  7. Conditional Expressions & Equality
  8. Blocks
  9. Comments
  10. Whitespace
  11. Leading Commas
  12. Semicolons
  13. Type Casting & Coercion
  14. Naming Conventions
  15. Accessors
  16. Constructors
  17. jQuery
  18. Modules
  19. ES5 Compatibility
  20. Performance
  21. Resources
  22. In the Wild
  23. Translation
  24. The JavaScript Style Guide Guide
  25. Contributors
  26. License
  • Use the literal syntax for object creation.

    // badvaritem=newObject();// goodvaritem={};
  • Don't use reserved words as keys.

    // badvarsuperman={class: 'superhero',default: {clark: 'kent'},private: true};// goodvarsuperman={klass: 'superhero',defaults: {clark: 'kent'},hidden: true};

    [⬆]

  • Use the literal syntax for array creation

    // badvaritems=newArray();// goodvaritems=[];
  • For clarity and performance reasons, cache the length of your arrays in variables outside of the loop

    // badfor(vari=0;i<items.length;i++){// ...stuff...}// badfor(vari=0,len=items.length;i<len;i++){// ...stuff...}// goodvarlen=items.length;vari;for(i=0;i<len;i++){// ...stuff...}
  • Always use array#push when appending new values to an array.

    varsomeStack=[];// badsomeStack[someStack.length]='abracadabra';// goodsomeStack.push('abracadabra');
  • When you need to copy an array use Array#slice. jsPerf

    varlen=items.length;varitemsCopy=[];vari;// badfor(i=0;i<len;i++){itemsCopy[i]=items[i];}// gooditemsCopy=items.slice();
  • To convert an array-like object to an array, use Array#slice.

    functiontrigger(){varargs=Array.prototype.slice.call(arguments);
    ...
    }

    [⬆]

  • Use single quotes '' for strings

    // badvarname="Bob Parr";// goodvarname='Bob Parr';// badvarfullName="Bob "+this.lastName;// goodvarfullName='Bob '+this.lastName;// badvarfullName="<a href=\"/name\">Bob "+this.lastName+"</a>";// goodvarfullName='<a href="/name">Bob '+this.lastName+'</a>';
  • Use double quotes "" for interpreted strings inside templates.

    // badvarname=users['#{ getUser }'];// goodvarname=users["#{ getUser }"];
  • 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

    // badvarerrorMessage='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.';// badvarerrorMessage='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.';// goodvarerrorMessage='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.';
  • When programatically building up a string, use Array#join instead of string concatenation. Mostly for IE: jsPerf.

    varitems;varmessages;varlength;vari;messages=[{state: 'success',message: 'This one worked.'},{state: 'success',message: 'This one worked as well.'},{state: 'error',message: 'This one did not work.'}];length=messages.length;// badfunctioninbox(messages){items='<ul>';for(i=0;i<length;i++){items+='<li>'+messages[i].message+'</li>';}returnitems+'</ul>';}// goodfunctioninbox(messages){items=[];for(i=0;i<length;i++){items[i]=messages[i].message;}return'<ul><li>'+items.join('</li><li>')+'</li></ul>';}

    [⬆]

  • Function expressions:

    // anonymous function expressionvaranonymous=function(){returntrue;};// named function expressionvarnamed=functionnamed(){returntrue;};// 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, which is bad news bears.

  • Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement. Read ECMA-262's note on this issue.

    // badif(currentUser){functiontest(){console.log('Nope.');}}// goodif(currentUser){vartest=functiontest(){console.log('Yup.');};}
  • Never name a parameter arguments, this will take precedence over the arguments object that is given to every function scope.

    // badfunctionnope(name,options,arguments){// ...stuff...}// goodfunctionyup(name,options,args){// ...stuff...}

    [⬆]

  • Use dot notation when accessing properties.

    varluke={jedi: true,age: 28};// badvarisJedi=luke['jedi'];// goodvarisJedi=luke.jedi;
  • Use subscript notation [] when accessing properties with a variable.

    varusers={jane: {},john: {}};varuserName=getUsername();varuserObject=users[userName];

    [⬆]

  • 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.

    // badsuperPower=newSuperPower();// goodvarsuperPower=newSuperPower();
  • Use additional var declarations for multiple variables and declare each variable on a newline. This is useful when reordering variables and avoiding simple syntax mistakes.

    // badvaritems=getItems(),goSportsTeam=true,dragonball='z';// badvaritems=getItems(),goSportsTeam=true,dragonball='z';// goodvaritems=getItems();vargoSportsTeam=true;vardragonball='z';varlength;vari;
  • Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.

    // badfunction(){test();console.log('doing stuff..');//..other stuff..varname=getName();if(name==='test'){returnfalse;}returnname;}// goodfunction(){varname=getName();test();console.log('doing stuff..');//..other stuff..if(name==='test'){returnfalse;}returnname;}// badfunction(){varname=getName();if(!arguments.length){returnfalse;}returntrue;}// goodfunction(){if(!arguments.length){returnfalse;}varname=getName();returntrue;}

    [⬆]

  • 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 evalute 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}
  • Use shortcuts.

    // badif(name!==''){// ...stuff...}// goodif(name){// ...stuff...}
  • For more information see Truth Equality and JavaScript by Angus Croll

    [⬆]

  • Use braces with all blocks.

    // badif(test)returnfalse;// badif(test)returnfalse;// goodif(test){returnfalse;}
  • Always put blocks and curlys on their own lines.

    // badif(test){returnfalse;}// goodif(test){returnfalse;}// badfunction(){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}

    [⬆]

  • Documentation is highly recommended on Utility Modules. It is optional on all other types of Modules.

  • Don't over document. Opt for descriptive names of variables, functions, and returns over documenting the obvious.

  • Use JSDoc notation for commenting guidelines.

  • Use /** ... */ for multiline comments.

    // bad// make() returns a new element// based on the passed in tag name//// @param {String} tag// @return {Element} elementfunctionmake(tag){// ...stuff...returnelement;}// good/** * make() returns a new element * based on the passed in tag name * * @param {String} tag * @return {Element} element */functionmake(tag){// ...stuff...returnelement;}
  • Use // for single line comments. Always place single line comments on a newline above the subject of the comment. Put an empty line before the comment.

    // badvaractive=true;// is current tab// good// is current tabvaractive=true;// badfunctiongetType(){console.log('fetching type...');// set the default type to 'no type'vartype=this._type||'no type';returntype;}// goodfunctiongetType(){console.log('fetching type...');// set the default type to 'no type'vartype=this._type||'no type';returntype;}
  • Always specify types and values for all parameters and return values. Ideally, provide a description for the function and parameters as well.

```javascript
// bad
function make(tag) {
// ...stuff...
}
// good
/**
* @param {String} tag
* @return {Element} element
*/
function make(tag) {
// ...stuff...
}
// best
/**
* Returns a new element based on the passed in tag name.
*
* @param {String} tag
* Tag to create. -eg 'a', 'span', 'strong'
* @return {Element} element
* DOM element object.
*/
function make(tag) {
// ...stuff...
return element;
}
```
**[[⬆]](#TOC)**
  • Use soft tabs set to 2 spaces

    // badfunction(){∙∙∙∙varname;}// badfunction(){∙varname;}// goodfunction(){∙∙varname;}
  • Place 1 space before the leading brace.

    // badfunctiontest(){console.log('test');}// goodfunctiontest(){console.log('test');}// baddog.set('attr',{age: '1 year',breed: 'Bernese Mountain Dog'});// gooddog.set('attr',{age: '1 year',breed: 'Bernese Mountain Dog'});
  • Use indentation when making long method chains.

    // bad$('#items').find('.selected').highlight().end().find('.open').updateCount();// good$('#items').find('.selected').highlight().end().find('.open').updateCount();// badvarleds=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);// goodvarleds=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);

    [⬆]

  • Nope.

    // badvaronce,upon,aTime;// badvarhero={firstName: 'Bob',lastName: 'Parr',heroName: 'Mr. Incredible',superPower: 'strength'};// goodvarhero={firstName: 'Bob',lastName: 'Parr',heroName: 'Mr. Incredible',superPower: 'strength'};

    [⬆]

  • Yup.

    // bad(function(){varname='Skywalker'returnname})()// good(function(){varname='Skywalker';returnname;})();// good;(function(){varname='Skywalker';returnname;})();

    [⬆]

  • Perform type coercion at the beginning of the statement.

  • Strings:

    // => this.reviewScore = 9;// badvartotalScore=this.reviewScore+'';// goodvartotalScore=''+this.reviewScore;// badvartotalScore=''+this.reviewScore+' total score';// goodvartotalScore=this.reviewScore+' total score';
  • Numbers:

  • Use parseInt for Numbers and always with a radix for type casting.

  • If for whatever reason you are doing something wild and parseInt is your bottleneck and need to use Bitshift for performance reasons, leave a comment explaining why and what you're doing.

    varinputValue='4';// badvarval=newNumber(inputValue);// badvarval=+inputValue;// goodvarval=parseInt(inputValue,10);

    [⬆]

  • Avoid single letter names. Be descriptive with your naming. These get Uglified anyways.

    // badfunctionq(){// ...stuff...}// goodfunctionquery(){// ..stuff..}
  • Use PascalCase when naming Views, Constructors, Classes, Models, and Collections.

    // badfunctionuser(options){this.name=options.name;}varbad=newuser({name: 'nope'});// goodfunctionUser(options){this.name=options.name;}vargood=newUser({name: 'yup'});
  • Use lower camelCase for everything else (e.g.- objects, functions, and instances).

    // badvarOBJEcttsssss={};varthis_is_my_object={};varthis-is-my-object={};functionc(){};varu=newuser({name: 'Bob Parr'});// goodvarthisIsMyObject={};functionthisIsMyFunction(){};varuser=newUser({name: 'Bob Parr'});
  • When saving a reference to this use self.

    // badfunction(){varthat=this;returnfunction(){console.log(that);};}// goodfunction(){varself=this;returnfunction(){console.log(self);};}
  • Name your functions. This is helpful for stack traces.

    // badvarlog=function(msg){console.log(msg);};// goodvarlog=functionlog(msg){console.log(msg);};

    [⬆]

  • Accessor functions for properties are not required

  • If you do make accessor functions, always prepend with get and set. Eg- getVal() and setVal('hello').

    // baddragon.age();// gooddragon.getAge();// baddragon.age(25);// gooddragon.setAge(25);
  • If the property is a boolean, use isVal() or hasVal()

    // badif(!dragon.age()){returnfalse;}// goodif(!dragon.hasAge()){returnfalse;}
  • It's okay to create get() and set() functions, but be consistent.

    functionJedi(options){options||(options={});varlightsaber=options.lightsaber||'blue';this.set('lightsaber',lightsaber);}Jedi.prototype.set=function(key,val){this[key]=val;};Jedi.prototype.get=function(key){returnthis[key];};

    [⬆]

  • 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!

    functionJedi(){console.log('new jedi');}// badJedi.prototype={fight: functionfight(){console.log('fighting');},block: functionblock(){console.log('blocking');}};// goodJedi.prototype.fight=functionfight(){console.log('fighting');};Jedi.prototype.block=functionblock(){console.log('blocking');};
  • Methods can return this to help with method chaining.

    // badJedi.prototype.jump=function(){this.jumping=true;returntrue;};Jedi.prototype.setHeight=function(height){this.height=height;};varluke=newJedi();luke.jump();// => trueluke.setHeight(20)// => undefined// goodJedi.prototype.jump=function(){this.jumping=true;returnthis;};Jedi.prototype.setHeight=function(height){this.height=height;returnthis;};varluke=newJedi();luke.jump().setHeight(20);

    [⬆]

  • Prefix jQuery object variables with a $.

    // badvarsidebar=$('.sidebar');// goodvar$sidebar=$('.sidebar');// badvar$primary_nav=$('#primary-nav');// goodvar$primaryNav=$('#primary-nav');
  • If a jQuery lookup is performed more than once, cache the jQuery object.

    // badfunctionsetSidebar(){$('.sidebar').hide();// ...stuff...$('.sidebar').css({'background-color': 'pink'});}// badfunctiongetSideBarHeight(){var$sidebar=$('.sidebar');$sidebar.height();}// goodfunctiongetSideBarHeight(){$('.sidebar').height();}// goodfunctionsetSidebar(){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$('.sidebar','ul').hide();// bad$('.sidebar').find('ul').hide();// good$('.sidebar ul').hide();// good$('.sidebar > ul').hide();// good (slower)$sidebar.find('ul');// good (faster)$($sidebar[0]).find('ul');
  • Don't combine elements with a class or ID as part of the selector. If this results in selecting elements you don't want, you probably need to refactor your DOM.

    // bad$('form#new_user').submit();// bad$('li.user').hide();// good$('#new_user').submit();// good$('.user').hide();

    [⬆]

  • We use the JavaScript Module Pattern, as defined by Ben Cherry. Read up on it here.

  • Files should be named with camelCase, live in their appropriate folder (views/ utils/ etc), and match the name of the single export.

  • Always declare 'use strict;' at the top of the module.

  • Always return the original module object.

  • If you need to reference any other global objects, pass it to the module's arguments to help provide faster lookups and prevent linting errors.

    /*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, jquery:true, indent:2, maxerr:100 *//*@namespace viewName@memberOf haw.views*/varhaw=(function(module,$){'use strict';// Module Namespace Extensionvarviews=module.views=module.views||{};varviewName=views.viewName=views.viewName||{};// Private Variablesvarfoo="bar";// Private MethodfunctionprivateMethod(){}// Public APIviewName.publicMethod=function(){};// Return the extended modulereturnmodule;}(haw||{},jQuery));

    [⬆]

[⬆]

[⬆]

Read This

Other Styleguides

Other Styles

Books

Blogs

Additional Articles

[⬆]

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.

This style guide is also available in other languages:

(The MIT License)

Copyright (c) 2012 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.

[⬆]

About

JavaScript Style Guide

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors