Skip to content
This repository was archived by the owner on Feb 12, 2022. It is now read-only.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

128 Commits

Repository files navigation

ExactTarget JavaScript Style Guide

A mostly reasonable approach to JavaScript

Table of Contents

  1. Types
  2. Objects
  3. Arrays
  4. Strings
  5. Functions
  6. Properties
  7. Variables
  8. Hoisting
  9. Comparison Operators & Equality
  10. Blocks
  11. Comments
  12. Whitespace
  13. Commas
  14. Semicolons
  15. Type Casting & Coercion
  16. Naming Conventions
  17. Accessors
  18. Constructors
  19. Modules
  20. jQuery
  21. ECMAScript 5 Compatibility
  22. Testing
  23. Performance
  24. Editorconfig Setup / Use
  25. Resources
  26. In the Wild
  27. The JavaScript Style Guide Guide
  28. Contributors
  29. License

Types

  • Primitives: When you access a primitive type you work directly on its value.

    • string
    • number
    • boolean
    • null
    • undefined
    varfoo=1;varbar=foo;bar=9;console.log(foo,bar);// => 1, 9
  • Complex: When you access a complex type you work on a reference to its value.

    • object
    • array
    • function
    varfoo=[1,2];varbar=foo;bar[0]=9;console.log(foo[0],bar[0]);// => 9, 9

⬆ back to top

Objects

  • Use the literal syntax for object creation.

    // badvaritem=newObject();// goodvaritem={};
  • Don't use reserved words as keys. It won't work in IE8. More info.

    // badvarsuperman={class: 'superhero',default: {clark: 'kent'},private: true};// goodvarsuperman={cssClass: 'superhero',defaults: {clark: 'kent'},hidden: true};
  • Use readable synonyms in place of reserved words.

    // badvarsuperman={class: 'alien'};// badvarsuperman={klass: 'alien'};// goodvarsuperman={type: 'alien'};

⬆ back to top

Arrays

  • Use the literal syntax for array creation.

    // badvaritems=newArray();// goodvaritems=[];
  • Use Array#push instead of direct assignment to add items 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);
    ...
    }

⬆ back to top

Strings

  • Use single quotes '' for strings.

    // badvarname="Bob Parr";// goodvarname='Bob Parr';// badvarfullName="Bob "+this.lastName;// goodvarfullName='Bob '+this.lastName;

⬆ back to top

Functions

  • Function expressions:

    // anonymous function as event handler$el.on('click',function(){returntrue;});// optional name to aid debugging with stack traces$el.on('click',functionelClick(){returntrue;});// anonymous function as methodMyObject.prototype.isTrue=function(){returntrue;};// immediately-invoked function expression (IIFE)(function(){console.log('Welcome to the Internet. Please follow me.');})();
  • Function declarations:

    // use a named declaration when appropriate mainly// for internal helper logic and organizationfunctionnamedFunction(){returntrue;}
  • 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.');}}// goodvartest;if(currentUser){test=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...}

⬆ back to top

Properties

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

    varluke={jedi: true,age: 28};functiongetProp(prop){returnluke[prop];}varisJedi=getProp('jedi');

⬆ back to top

Variables

  • 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 one var declaration per variable. 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.

    // badvaritems=getItems(),goSportsTeam=true,dragonball='z';// bad// (compare to above, and try to spot the mistake)varitems=getItems(),goSportsTeam=true;dragonball='z';// goodvaritems=getItems();vargoSportsTeam=true;vardragonball='z';
  • Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables. Multiple unassigned variables can be declared in a single-line var declaration.

    // goodvaritems=getItems();vargoSportsTeam=true;vari,j,length;
  • 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;}// bad - unnecessary function callfunction(){varname=getName();if(!arguments.length){returnfalse;}this.setFirstName(name);returntrue;}// goodfunction(){varname;if(!arguments.length){returnfalse;}name=getName();this.setFirstName(name);returntrue;}

⬆ back to top

Hoisting

  • Variable declarations get hoisted to the top of their scope, but their assignment does not.

    // we know this wouldn't work (assuming there// is no notDefined global variable)functionexample(){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.functionexample(){console.log(declaredButNotAssigned);// => undefinedvardeclaredButNotAssigned=true;}// The interpreter is hoisting the variable// declaration to the top of the scope,// which means our example could be rewritten as:functionexample(){vardeclaredButNotAssigned;console.log(declaredButNotAssigned);// => undefineddeclaredButNotAssigned=true;}
  • Anonymous function expressions hoist their variable name, but not the function assignment.

    functionexample(){console.log(anonymous);// => undefinedanonymous();// => TypeError anonymous is not a functionvaranonymous=function(){console.log('anonymous function expression');};}
  • Named function expressions hoist the variable name, not the function name or the function body.

    functionexample(){console.log(named);// => undefinednamed();// => TypeError named is not a functionsuperPower();// => ReferenceError superPower is not definedvarnamed=functionsuperPower(){console.log('Flying');};}// the same is true when the function name// is the same as the variable name.functionexample(){console.log(named);// => undefinednamed();// => TypeError named is not a functionvarnamed=functionnamed(){console.log('named');};}
  • Function declarations hoist their name and the function body.

    functionexample(){superPower();// => FlyingfunctionsuperPower(){console.log('Flying');}}
  • For more information refer to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Comparison Operators & Equality

  • Use === and !== over == and !=.

  • Conditional statements such as the if statement evaluate their expression using coercion with the ToBoolean 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 is an object, objects evaluate to true}
  • Use shortcuts.

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

⬆ back to top

Blocks

  • Use braces with all multi-line blocks.

    // badif(test)returnfalse;// acceptable (only for very simple statements and early function return)if(test)returnfalse;// goodif(test){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}
  • If you're using multi-line blocks with if and else, put else on the same line as your if block's closing brace.

    // badif(test){thing1();thing2();}else{thing3();}// goodif(test){thing1();thing2();}else{thing3();}

⬆ back to top

Comments

  • Use /** ... */ for multi-line 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} 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. 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;}
  • Prefixing your comments with FIXME or TODO 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 are FIXME -- need to figure this out or TODO -- need to implement.

  • Use // FIXME: to annotate problems.

    functionCalculator(){// FIXME: shouldn't use a global heretotal=0;returnthis;}
  • Use // TODO: to annotate solutions to problems.

    functionCalculator(){// TODO: total should be configurable by an options paramthis.total=0;returnthis;}

⬆ back to top

Whitespace

  • Use tabs. One per indent level. This allows developers to choose their preferred display width.

    // 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'});
  • Place 1 space before the opening parenthesis in control statements (if, while etc.). Place no space before the argument list in function calls and declarations.

    // badif(isJedi){fight();}// goodif(isJedi){fight();}// badfunctionfight(){console.log('Swooosh!');}// goodfunctionfight(){console.log('Swooosh!');}
  • Place 1 space before anonymous function parenthesis.

    // badfunction(){varname;}// goodfunction(){varname;}
  • Set off operators with spaces.

    // badvarx=y+5;// goodvarx=y+5;
  • End files with a single newline character.

    // bad(function(global){// ...stuff...})(this);
    // bad(function(global){// ...stuff...})(this);
    // good(function(global){// ...stuff...})(this);
  • Use indentation when making long method chains. Long method chains should be avoided except in cases of a performance benefit or significant readability benefit.

// 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);

⬆ back to top

Commas

  • Leading commas: Nope.

    // badvarstory=[once,upon,aTime];// goodvarstory=[once,upon,aTime];// badvarhero={firstName: 'Bob',lastName: 'Parr',heroName: 'Mr. Incredible',superPower: 'strength'};// goodvarhero={firstName: 'Bob',lastName: 'Parr',heroName: 'Mr. Incredible',superPower: 'strength'};
  • Additional trailing comma: Nope. This can cause problems with IE6/7 and IE9 if it's in quirksmode. Also, in some implementations of ES3 would add length to an array if it had an additional trailing comma. This was clarified in ES5 (source):

Edition 5 clarifies the fact that a trailing comma at the end of an ArrayInitialiser does not add to the length of the array. This is not a semantic change from Edition 3 but some implementations may have previously misinterpreted this.

```javascript
// bad
var hero = {
firstName: 'Kevin',
lastName: 'Flynn',
};
var heroes = [
'Batman',
'Superman',
];
// good
var hero = {
firstName: 'Kevin',
lastName: 'Flynn'
};
var heroes = [
'Batman',
'Superman'
];
```

⬆ back to top

Semicolons

  • Yup.

    // bad(function(){varname='Skywalker'returnname})()// good(function(){varname='Skywalker';returnname;})();// good (guards against the function becoming an argument when two files with IIFEs are concatenated);(function(){varname='Skywalker';returnname;})();

    Read more.

⬆ back to top

Type Casting & Coercion

  • 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';
  • Use parseInt for Numbers and always with a radix for type casting.

    varinputValue='4';// badvarval=newNumber(inputValue);// badvarval=+inputValue;// badvarval=inputValue>>0;// badvarval=parseInt(inputValue);// goodvarval=Number(inputValue);// goodvarval=parseInt(inputValue,10);
  • If for whatever reason you are doing something wild and parseInt is your bottleneck and need to use Bitshift for performance reasons, 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. */varval=inputValue>>0;
  • 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//=> 21474836472147483648>>0//=> -21474836482147483649>>0//=> -2147483647
  • Booleans:

    varage=0;// badvarhasAge=newBoolean(age);// goodvarhasAge=Boolean(age);// goodvarhasAge=!!age;

⬆ back to top

Naming Conventions

  • Avoid single letter names. Be descriptive with your naming.

    // badfunctionq(){// ...stuff...}// goodfunctionquery(){// ..stuff..}
  • Use camelCase when naming objects, functions, and instances.

    // badvarOBJEcttsssss={};varthis_is_my_object={};varo={};functionc(){}varu=newuser({name: 'Bob Parr'});// goodvarthisIsMyObject={};functionthisIsMyFunction(){};varuser=newUser({name: 'Bob Parr'});
  • Use PascalCase when naming constructors or classes.

    // badfunctionuser(options){this.name=options.name;}varbad=newuser({name: 'nope'});// goodfunctionUser(options){this.name=options.name;}vargood=newUser({name: 'yup'});
  • Use a leading underscore _ when naming private properties.

    // badthis.__firstName__='Panda';this.firstName_='Panda';// goodthis._firstName='Panda';
  • When saving a reference to this use self.

    // badfunction(){varthat=this;returnfunction(){console.log(that);};}// badfunction(){var_this=this;returnfunction(){console.log(_this);};}// 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);};

⬆ back to top

Accessors

  • Accessor functions for properties are not required.

  • If you do make accessor functions use 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];};

⬆ back to top

Constructors

  • Assign methods to the prototype object, instead of overwriting the prototype with a new object. Overwriting the prototype makes inheritance impossible: by resetting the prototype you'll overwrite the base!

    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);
  • It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.

    functionJedi(options){options||(options={});this.name=options.name||'no name';}Jedi.prototype.getName=functiongetName(){returnthis.name;};Jedi.prototype.toString=functiontoString(){return'Jedi - '+this.getName();};

⬆ back to top

Modules

⬆ back to top

jQuery

  • Prefix jQuery object variables with a $.

    // badvarsidebar=$('.sidebar');// goodvar$sidebar=$('.sidebar');
  • Cache jQuery lookups.

    // badfunctionsetSidebar(){$('.sidebar').hide();// ...stuff...$('.sidebar').css({'background-color': 'pink'});}// 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$('ul','.sidebar').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');

⬆ back to top

ECMAScript 5 Compatibility

⬆ back to top

Testing

  • Yup.

    function(){returntrue;}

⬆ back to top

Performance

⬆ back to top

  • Usually for a project with more than one developer involved, it is essentially important for the project to define and maintain a consistent coding style. Most code editors and IDEs, such as Vim, Emacs, Code::Blocks, provide settings related to coding styles, such as the width of tab, the size of indentation, end of line, etc. However, it is hard to provide the same settings for different Editors and IDEs: we have to maintain many config files for different editors and IDEs, such as .vimrc for Vim, .emacs for Emacs. In order to solve this, EditorConfig was born. By defining coding style in files named .editorconfig, the EditorConfig plugins for different editors and IDEs will automatically adjust your coding style.
  • To use EditorConfig, you have to download the corresponding EditorConfig plugins for your Editor or IDE. Follow the installation instructions to install them.
  • The "base" .editorconfig file goes in the root directory. You can have other config files in specific folders if wanted. The only difference would be at the top of the file to remove root = true from any file that isn't the root.

⬆ back to top

Resources

Read This

Other Style Guides

Other Styles

Further Reading

Books

Blogs

Podcasts

⬆ back to top

The JavaScript Style Guide Guide

License

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


Copyright (c) 2014 ExactTarget, Inc.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

⬆ back to top

About

JavaScript Style Guide

Resources

Stars

50 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors