Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

JavaScript Style Guide

NotificationsYou must be signed in to change notification settings

grooveshark/javascript

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 

Repository files navigation

A mostly reasonable approach to JavaScript

Forked and slightly modified from Airbnb's Style Guide, but still reasonable

  1. Types
  2. Objects
  3. Arrays
  4. Strings
  5. Functions
  6. Properties
  7. Variables
  8. Hoisting
  9. Conditional Expressions & Equality
  10. Blocks
  11. Comments
  12. Whitespace
  13. Commas
  14. Semicolons
  15. Type Casting & Coercion
  16. Naming Conventions
  17. Accessors
  18. Constructors
  19. Events
  20. jQuery
  21. ES5 Compatibility
  22. Testing
  23. Performance
  24. Resources
  25. In the Wild
  26. Translation
  27. The JavaScript Style Guide Guide
  28. Contributors
  29. License
  • Primitives: When you access a primitive type you work directly on its value

    • string
    • number
    • boolean
    • null
    • undefined
    varfoo=1,bar=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],bar=foo;bar[0]=9;console.log(foo[0],bar[0]);// => 9, 9

    [⬆]

  • Use the literal syntax for object creation.

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

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

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

    [⬆]

  • Use the literal syntax for array creation

    // badvaritems=newArray();// goodvaritems=[];
  • If you don't know array length use Array#push.

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

    varlen=items.length,itemsCopy=[],i;// 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;
  • 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,messages,length,i;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 ablock 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 parameterarguments, this will take precedence over thearguments 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.

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

    [⬆]

  • Always usevar 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 onevar declaration for multiple variables and declare each variable on a newline.

    // badvaritems=getItems();vargoSportsTeam=true;vardragonball='z';// goodvaritems=getItems(),goSportsTeam=true,dragonball='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.

    // badvari,len,dragonball,items=getItems(),goSportsTeam=true;// badvari,items=getItems(),dragonball,goSportsTeam=true,len;// goodvaritems=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.

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

    [⬆]

  • 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)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 toJavaScript Scoping & Hoisting byBen Cherry

    [⬆]

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

  • Conditional expressions are evaluated using coercion with theToBoolean method and always follow these simple rules:

    • Objects evaluate totrue
    • Undefined evaluates tofalse
    • Null evaluates tofalse
    • Booleans evaluate tothe value of the boolean
    • Numbers evalute tofalse if+0, -0, or NaN, otherwisetrue
    • Strings evaluate tofalse if an empty string'', otherwisetrue
    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 seeTruth Equality and JavaScript by Angus Croll

    [⬆]

  • Use braces with all multi-line blocks.

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

    [⬆]

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

  • 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;}
  **[[⬆]](#TOC)**## <a name='whitespace'>Whitespace</a>- Use soft tabs set to 4 spaces  ```javascript  // bad  function() {  ∙∙var name;  }  // bad  function() {  ∙var name;  }  // good  function() {  ∙∙∙∙var name;  }  ```- Place 1 space before the leading brace.  ```javascript  // 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'  });  ```- Place an empty newline at the end of the file.  ```javascript  // bad  (function(global) {      // ...stuff...  })(this);  ```  ```javascript  // good  (function(global) {      // ...stuff...  })(this);  ```  **[[⬆]](#TOC)**## <a name='commas'>Commas</a>- Leading commas: **Nope.**  ```javascript  // bad  var once    , upon    , aTime;  // good  var once,      upon,      aTime;  // bad  var hero = {      firstName: 'Bob'    , lastName: 'Parr'    , heroName: 'Mr. Incredible'    , superPower: 'strength'  };  // good  var hero = {      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](http://es5.github.io/#D)):> 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'  ];  ```  **[[⬆]](#TOC)**## <a name='semicolons'>Semicolons</a>- **Yup.**  ```javascript  // bad  (function() {      var name = 'Skywalker'      return name  })()  // good  (function() {      var name = 'Skywalker';      return name;  })();  ```  **[[⬆]](#TOC)**## <a name='type-coercion'>Type Casting & Coercion</a>- Perform type coercion at the beginning of the statement.- Strings:  ```javascript  //  => this.reviewScore = 9;  // bad  var totalScore = this.reviewScore + '';  // good  var totalScore = '' + this.reviewScore;  // bad  var totalScore = '' + this.reviewScore + ' total score';  // good  var totalScore = this.reviewScore + ' total score';  ```- Use `parseInt` for Numbers and always with a radix for type casting, if you want invalid value to be NaN or the radix is not 10.- If you want invalid values to return 0 and it is a decimal value, use Grooveshark's custom method ```_.toInt()```  ```javascript  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);  // good  var val = _.toInt(inputValue);  ```- If for whatever reason you are doing something wild and `parseInt` is your bottleneck and need to use Bitshift for [performance reasons](http://jsperf.com/coercion-vs-casting/3), don't.- Use Grooveshark's custom method _.toInt() instead - it uses bitshifting for performance in the browsers for which it makes a difference.- Booleans:  ```javascript  var age = 0;  // bad  var hasAge = new Boolean(age);  // good  var hasAge = Boolean(age);  // good  var hasAge = !!age;  ```  **[[⬆]](#TOC)**## <a name='naming-conventions'>Naming Conventions</a>- Avoid single letter names. Be descriptive with your naming.  ```javascript  // bad  function q() {      // ...stuff...  }  // good  function query() {      // ..stuff..  }  ```- Use headlessCamels when naming objects, functions, and instances  ```javascript  // bad  var OBJEcttsssss = {};  var this_is_my_object = {};  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 ProudCamels when naming constructors or classes  ```javascript  // bad  function user(options) {      this.name = options.name;  }  var bad = new user({      name: 'nope'  });  // good  function User(options) {      this.name = options.name;  }  var good = new User({      name: 'yup'  });  ```- Use a leading underscore `_` when naming private properties or methods  ```javascript  // bad  this.__firstName__ = 'Panda';  this.firstName_ = 'Panda';  // good  this._firstName = 'Panda';  ```- When saving a reference to `this` use `_this`.  ```javascript  // 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);      };  }  ```- Name your functions. This is helpful for stack traces.  ```javascript  // bad  var log = function(msg) {      console.log(msg);  };  // good  var log = function log(msg) {      console.log(msg);  };  ```  **[[⬆]](#TOC)**## <a name='accessors'>Accessors</a>- Accessor functions for properties are not required- If you do make accessor functions use getVal() and setVal('hello')- Grooveshark Note: Nope - Use a Backbone Model if you need getters/setters  ```javascript  // bad  dragon.age();  // good  dragon.getAge();  // bad  dragon.age(25);  // good  dragon.setAge(25);  ```- If the property is a boolean, use isVal() or hasVal()  ```javascript  // bad  if (!dragon.age()) {      return false;  }  // good  if (!dragon.hasAge()) {      return false;  }  ```- It's okay to create get() and set() functions, but be consistent.  ```javascript  function Jedi(options) {      options || (options = {});      var lightsaber = options.lightsaber || 'blue';      this.set('lightsaber', lightsaber);  }  Jedi.prototype.set = function(key, val) {      this[key] = val;  };  Jedi.prototype.get = function(key) {      return this[key];  };  ```  **[[⬆]](#TOC)**## <a name='constructors'>Constructors</a>- 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!- Grooveshark Note: Usually you'll never have to worry about this, because Backbone  ```javascript  function Jedi() {      console.log('new jedi');  }  // bad  Jedi.prototype = {      fight: function fight() {          console.log('fighting');      },      block: function block() {          console.log('blocking');      }  };  // good  Jedi.prototype.fight = function fight() {      console.log('fighting');  };  Jedi.prototype.block = function block() {      console.log('blocking');  };  ```- Methods can return `this` to help with method chaining.  ```javascript  // bad  Jedi.prototype.jump = function() {      this.jumping = true;      return true;  };  Jedi.prototype.setHeight = function(height) {      this.height = height;  };  var luke = new Jedi();  luke.jump(); // => true  luke.setHeight(20) // => undefined  // good  Jedi.prototype.jump = function() {      this.jumping = true;      return this;  };  Jedi.prototype.setHeight = function(height) {      this.height = height;      return this;  };  var luke = new Jedi();  luke.jump()    .setHeight(20);  ```- It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.  ```javascript  function Jedi(options) {      options || (options = {});      this.name = options.name || 'no name';  }  Jedi.prototype.getName = function getName() {      return this.name;  };  Jedi.prototype.toString = function toString() {      return 'Jedi - ' + this.getName();  };  ```  **[[⬆]](#TOC)**## <a name='events'>Events</a>- 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:  ```js  // bad  $(this).trigger('listingUpdated', listing.id);  ...  $(this).on('listingUpdated', function(e, listingId) {      // do something with listingId  });  ```  prefer:  ```js  // good  $(this).trigger('listingUpdated', { listingId : listing.id });  ...  $(this).on('listingUpdated', function(e, data) {      // do something with data.listingId  });  ```**[[⬆]](#TOC)**## <a name='jquery'>jQuery</a>- Prefix jQuery object variables with a `$`.  ```javascript  // bad  var sidebar = $('.sidebar');  // good  var $sidebar = $('.sidebar');  ```- Cache jQuery lookups.  ```javascript  // 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](http://jsperf.com/jquery-find-vs-context-sel/16)- Use `find` with scoped jQuery object queries.  ```javascript  // 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');  ```  **[[⬆]](#TOC)**## <a name='es5'>ECMAScript 5 Compatibility</a>- Refer to [Kangax](https://twitter.com/kangax/)'s ES5 [compatibility table](http://kangax.github.com/es5-compat-table/)**[[⬆]](#TOC)**## <a name='testing'>Testing</a>- **Yup.**  ```javascript  function() {      return true;  }  ```  **[[⬆]](#TOC)**## <a name='performance'>Performance</a>- [On Layout & Web Performance](http://kellegous.com/j/2013/01/26/layout-performance/)- [String vs Array Concat](http://jsperf.com/string-vs-array-concat/2)- [Try/Catch Cost In a Loop](http://jsperf.com/try-catch-in-loop-cost)- [Bang Function](http://jsperf.com/bang-function)- [jQuery Find vs Context, Selector](http://jsperf.com/jquery-find-vs-context-sel/13)- [innerHTML vs textContent for script text](http://jsperf.com/innerhtml-vs-textcontent-for-script-text)- [Long String Concatenation](http://jsperf.com/ya-string-concat)- Loading...**[[⬆]](#TOC)**## <a name='resources'>Resources</a>**Read This**- [Annotated ECMAScript 5.1](http://es5.github.com/)**Other Styleguides**- [Google JavaScript Style Guide](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml)- [jQuery Core Style Guidelines](http://docs.jquery.com/JQuery_Core_Style_Guidelines)- [Principles of Writing Consistent, Idiomatic JavaScript](https://github.com/rwldrn/idiomatic.js/)**Other Styles**- [Naming this in nested functions](https://gist.github.com/4135065) - Christian Johansen- [Conditional Callbacks](https://github.com/airbnb/javascript/issues/52)**Further Reading**- [Understanding JavaScript Closures](http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/) - Angus Croll**Books**- [#"hidden" data-csrf="true" value="4d7SynlxGiwyMEh4E9K5dcu9N38VeGaifh40y+/SCf10aalxWrEhAM9dKoj6DF9xNvlZZ03jf7T57JbrFZfJzg==" />

About

JavaScript Style Guide

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp