Skip to content

Latest commit

History

324 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Jam3 JavaScript Style Guide

Make It Happen and Don't Fuck It Up

Table of Contents

  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. Modules
  21. jQuery
  22. Testing
  23. Performance
  24. Resources
  25. In the Wild
  26. Translation
  27. The JavaScript Style Guide Guide
  28. Chat With Us About Javascript
  29. Contributors
  30. 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={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'};

⬆ back to top

Arrays

  • 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;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;
  • 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 programmatically 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>';}

⬆ back to top

Functions

  • 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.');}}// 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.

    // badvari,len,dragonball,items=getItems(),goSportsTeam=true;// badvari;varitems=getItems();vardragonball;vargoSportsTeam=true;varlen;// goodvaritems=getItems();vargoSportsTeam=true;vardragonball;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;}
  • Do not visually line up variables

    // badvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';// goodvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';

⬆ back to top

Hoisting

  • 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 to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Conditional Expressions & Equality

  • 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 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;// goodif(test)returnfalse;// goodif(test){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}

⬆ back to top

Comments

  • Use /** ... */ to document public function definitions. 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;}
  • Use // for multiline comments when a single line comment is longer than 80 charachters. Or use /* .. */

    // bad// this method will return a fantabulous variable that you can use to do lots of calculations with. If you don't know how to use it see the docs at http://someFakeSite.comvarfantabulousValue=fantabulous();// good// this method will return a fantabulous variable that you can use to do// lots of calculations with. If you don't know how to use it see the docs // at http://someFakeSite.comvarfantabulousValue=fantabulous();// good/* * this method will return a fantabulous variable that you can use to do * lots of calculations with. If you don't know how to use it see the docs  * at http://someFakeSite.com */varfantabulousValue=fantabulous();
  • 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](#table-of-contents)**
## Whitespace
- Use soft tabs set to 2 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'
});
```
- Set off operators with spaces.
```javascript
// bad
var x=y+5;
// good
var x = y + 5;
```
- End files with a single newline character.
```javascript
// bad
(function(global) {
// ...stuff...
})(this);
```
```javascript
// bad
(function(global) {
// ...stuff...
})(this);↵
↵
```
```javascript
// good
(function(global) {
// ...stuff...
})(this);↵
```
- Use indentation when making long method chains. Use a leading dot, which
emphasizes that the line is a method call, not a new statement.
```javascript
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// bad
$('#items').
find('selected').
highlight().
end().
find('.open').
updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
// bad
var leds = 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);
// good
var leds = 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);
```
- Leave a blank line after blocks and before the next statement
```javascript
// bad
if (foo) {
return bar;
}
return baz;
// good
if (foo) {
return bar;
}
return baz;
// bad
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
// good
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
```
- Magic Numbers and Fancy Stuff should be commented. Magic Numbers are constant values used for calculations. Fancy Stuff are things out of the norm done with good reason.
```javascript
// Magic Numbers
// +10 to move over from border
element.style.left = left + 10 + 'px';
// Fancy Stuff
// parseInt was the reason my code was slow.
// Bitshifting the String to coerce it to a
// Number made it a lot faster.
var val = '10' >> 0;
```
**[⬆ back to top](#table-of-contents)**
## Commas
- Leading commas: **Nope.**
```javascript
// bad
var story = [
once
, upon
, aTime
];
// good
var story = [
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'
];
```
**[⬆ back to top](#table-of-contents)**
## Semicolons
- **Yup.**
```javascript
// bad
(function() {
var name = 'Skywalker'
return name
})()
// good
(function() {
var name = 'Skywalker';
return name;
})();
// good (guards against the function becoming an argument when two files with IIFEs are concatenated)
;(function() {
var name = 'Skywalker';
return name;
})();
```
[Read more](http://stackoverflow.com/a/7365214/1712802).
**[⬆ back to top](#table-of-contents)**
## Type Casting & Coercion
- 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.
```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);
```
- 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), leave a comment explaining why and what you're doing.
```javascript
// 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;
```
- **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
```javascript
2147483647 >> 0 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
```
- Booleans:
```javascript
var age = 0;
// bad
var hasAge = new Boolean(age);
// bad
var hasAge = !!age;
// good
var hasAge = Boolean(age);
// good
var hasAge = age !== undefined;
```
**[⬆ back to top](#table-of-contents)**
## Naming Conventions
- Avoid single letter names and abreviations. Be descriptive with your naming.
```javascript
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
// bad
var perc = 0;
// good
var percentage = 0;
```
- Use camelCase when naming objects, functions, and instances.
```javascript
// 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 PascalCase 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.
```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
```
- Use a leading underscore `_` when naming private methods. Private methods should exist outside of the scope of object and should be invoked using the call method.
```javascript
var dog = {
_name: 'Spot',
bark: function(sound) {
_bark.call( this, sound );
}
};
function _bark(sound) {
console.log(this._name + ':' + sound);
}
  • Boolean variables should prefixed with is or has.

    // badvarcat=false;vareggs=true;// goodvarisCat=false;varhasEggs=true;
  • When saving a reference to this use _this.

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

    // badvarlog=function(msg){console.log(msg);};// goodvarlog=functionlog(msg){console.log(msg);};
  • Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.

⬆ 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;}dragon.age(true);// goodif(!dragon.hasAge()){returnfalse;}drag.setHasAge(true);
  • 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];};
  • Getters and Setters via properties can be used in non processor intensive operations. Should be defined via Object.defineProperty on a prototype

Object.defineProperty(ObjecCar.prototype,'speed',{get: function(){returnthis._speed;},set: function(speed){this._speed=speed;}});

⬆ 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

Events

  • 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});

⬆ back to top

Modules

  • Modules should be built using the CommonJS pattern

    // Creating a module in ./doSomething.jsmodule.exports=functiondoSomething(){console.log('BOO YA!');};
    // Consuming module from ./doSomething.js in another filevardoSomething=require('./doSomething');doSomething();
  • Resuable modules should be distributed on NPM

⬆ back to top

jQuery

  • You should shy away from using jQuery. Instead use modules off NPM like:
    • dom-select
    • dom-style
    • dom-tree
    • dom-event
  • Visit https://github.com/npm-dom for more info.

⬆ back to top

Performance

⬆ back to top

Resources

Read This

Tools

Other Styleguides

Other Styles

Further Reading

Books

Blogs

⬆ back to top

License

(The MIT License)

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

⬆ back to top

};

About

JavaScript Style Guide

Resources

Code of conduct

Contributing

Stars

24 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - Experience-Monks/Javascript-Code-Conventions: JavaScript Style Guide · GitHub
Skip to content

Latest commit

History

324 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Jam3 JavaScript Style Guide

Make It Happen and Don't Fuck It Up

Table of Contents

  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. Modules
  21. jQuery
  22. Testing
  23. Performance
  24. Resources
  25. In the Wild
  26. Translation
  27. The JavaScript Style Guide Guide
  28. Chat With Us About Javascript
  29. Contributors
  30. 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={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'};

⬆ back to top

Arrays

  • 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;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;
  • 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 programmatically 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>';}

⬆ back to top

Functions

  • 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.');}}// 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.

    // badvari,len,dragonball,items=getItems(),goSportsTeam=true;// badvari;varitems=getItems();vardragonball;vargoSportsTeam=true;varlen;// goodvaritems=getItems();vargoSportsTeam=true;vardragonball;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;}
  • Do not visually line up variables

    // badvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';// goodvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';

⬆ back to top

Hoisting

  • 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 to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Conditional Expressions & Equality

  • 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 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;// goodif(test)returnfalse;// goodif(test){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}

⬆ back to top

Comments

  • Use /** ... */ to document public function definitions. 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;}
  • Use // for multiline comments when a single line comment is longer than 80 charachters. Or use /* .. */

    // bad// this method will return a fantabulous variable that you can use to do lots of calculations with. If you don't know how to use it see the docs at http://someFakeSite.comvarfantabulousValue=fantabulous();// good// this method will return a fantabulous variable that you can use to do// lots of calculations with. If you don't know how to use it see the docs // at http://someFakeSite.comvarfantabulousValue=fantabulous();// good/* * this method will return a fantabulous variable that you can use to do * lots of calculations with. If you don't know how to use it see the docs  * at http://someFakeSite.com */varfantabulousValue=fantabulous();
  • 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](#table-of-contents)**
## Whitespace
- Use soft tabs set to 2 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'
});
```
- Set off operators with spaces.
```javascript
// bad
var x=y+5;
// good
var x = y + 5;
```
- End files with a single newline character.
```javascript
// bad
(function(global) {
// ...stuff...
})(this);
```
```javascript
// bad
(function(global) {
// ...stuff...
})(this);↵
↵
```
```javascript
// good
(function(global) {
// ...stuff...
})(this);↵
```
- Use indentation when making long method chains. Use a leading dot, which
emphasizes that the line is a method call, not a new statement.
```javascript
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// bad
$('#items').
find('selected').
highlight().
end().
find('.open').
updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
// bad
var leds = 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);
// good
var leds = 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);
```
- Leave a blank line after blocks and before the next statement
```javascript
// bad
if (foo) {
return bar;
}
return baz;
// good
if (foo) {
return bar;
}
return baz;
// bad
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
// good
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
```
- Magic Numbers and Fancy Stuff should be commented. Magic Numbers are constant values used for calculations. Fancy Stuff are things out of the norm done with good reason.
```javascript
// Magic Numbers
// +10 to move over from border
element.style.left = left + 10 + 'px';
// Fancy Stuff
// parseInt was the reason my code was slow.
// Bitshifting the String to coerce it to a
// Number made it a lot faster.
var val = '10' >> 0;
```
**[⬆ back to top](#table-of-contents)**
## Commas
- Leading commas: **Nope.**
```javascript
// bad
var story = [
once
, upon
, aTime
];
// good
var story = [
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'
];
```
**[⬆ back to top](#table-of-contents)**
## Semicolons
- **Yup.**
```javascript
// bad
(function() {
var name = 'Skywalker'
return name
})()
// good
(function() {
var name = 'Skywalker';
return name;
})();
// good (guards against the function becoming an argument when two files with IIFEs are concatenated)
;(function() {
var name = 'Skywalker';
return name;
})();
```
[Read more](http://stackoverflow.com/a/7365214/1712802).
**[⬆ back to top](#table-of-contents)**
## Type Casting & Coercion
- 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.
```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);
```
- 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), leave a comment explaining why and what you're doing.
```javascript
// 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;
```
- **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
```javascript
2147483647 >> 0 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
```
- Booleans:
```javascript
var age = 0;
// bad
var hasAge = new Boolean(age);
// bad
var hasAge = !!age;
// good
var hasAge = Boolean(age);
// good
var hasAge = age !== undefined;
```
**[⬆ back to top](#table-of-contents)**
## Naming Conventions
- Avoid single letter names and abreviations. Be descriptive with your naming.
```javascript
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
// bad
var perc = 0;
// good
var percentage = 0;
```
- Use camelCase when naming objects, functions, and instances.
```javascript
// 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 PascalCase 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.
```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
```
- Use a leading underscore `_` when naming private methods. Private methods should exist outside of the scope of object and should be invoked using the call method.
```javascript
var dog = {
_name: 'Spot',
bark: function(sound) {
_bark.call( this, sound );
}
};
function _bark(sound) {
console.log(this._name + ':' + sound);
}
  • Boolean variables should prefixed with is or has.

    // badvarcat=false;vareggs=true;// goodvarisCat=false;varhasEggs=true;
  • When saving a reference to this use _this.

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

    // badvarlog=function(msg){console.log(msg);};// goodvarlog=functionlog(msg){console.log(msg);};
  • Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.

⬆ 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;}dragon.age(true);// goodif(!dragon.hasAge()){returnfalse;}drag.setHasAge(true);
  • 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];};
  • Getters and Setters via properties can be used in non processor intensive operations. Should be defined via Object.defineProperty on a prototype

Object.defineProperty(ObjecCar.prototype,'speed',{get: function(){returnthis._speed;},set: function(speed){this._speed=speed;}});

⬆ 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

Events

  • 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});

⬆ back to top

Modules

  • Modules should be built using the CommonJS pattern

    // Creating a module in ./doSomething.jsmodule.exports=functiondoSomething(){console.log('BOO YA!');};
    // Consuming module from ./doSomething.js in another filevardoSomething=require('./doSomething');doSomething();
  • Resuable modules should be distributed on NPM

⬆ back to top

jQuery

  • You should shy away from using jQuery. Instead use modules off NPM like:
    • dom-select
    • dom-style
    • dom-tree
    • dom-event
  • Visit https://github.com/npm-dom for more info.

⬆ back to top

Performance

⬆ back to top

Resources

Read This

Tools

Other Styleguides

Other Styles

Further Reading

Books

Blogs

⬆ back to top

License

(The MIT License)

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

⬆ back to top

};

About

JavaScript Style Guide

Resources

Code of conduct

Contributing

Stars

24 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Experience-Monks/Javascript-Code-Conventions: JavaScript Style Guide · GitHub
Skip to content

Latest commit

History

324 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Jam3 JavaScript Style Guide

Make It Happen and Don't Fuck It Up

Table of Contents

  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. Modules
  21. jQuery
  22. Testing
  23. Performance
  24. Resources
  25. In the Wild
  26. Translation
  27. The JavaScript Style Guide Guide
  28. Chat With Us About Javascript
  29. Contributors
  30. 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={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'};

⬆ back to top

Arrays

  • 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;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;
  • 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 programmatically 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>';}

⬆ back to top

Functions

  • 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.');}}// 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.

    // badvari,len,dragonball,items=getItems(),goSportsTeam=true;// badvari;varitems=getItems();vardragonball;vargoSportsTeam=true;varlen;// goodvaritems=getItems();vargoSportsTeam=true;vardragonball;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;}
  • Do not visually line up variables

    // badvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';// goodvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';

⬆ back to top

Hoisting

  • 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 to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Conditional Expressions & Equality

  • 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 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;// goodif(test)returnfalse;// goodif(test){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}

⬆ back to top

Comments

  • Use /** ... */ to document public function definitions. 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;}
  • Use // for multiline comments when a single line comment is longer than 80 charachters. Or use /* .. */

    // bad// this method will return a fantabulous variable that you can use to do lots of calculations with. If you don't know how to use it see the docs at http://someFakeSite.comvarfantabulousValue=fantabulous();// good// this method will return a fantabulous variable that you can use to do// lots of calculations with. If you don't know how to use it see the docs // at http://someFakeSite.comvarfantabulousValue=fantabulous();// good/* * this method will return a fantabulous variable that you can use to do * lots of calculations with. If you don't know how to use it see the docs  * at http://someFakeSite.com */varfantabulousValue=fantabulous();
  • 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](#table-of-contents)**
## Whitespace
- Use soft tabs set to 2 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'
});
```
- Set off operators with spaces.
```javascript
// bad
var x=y+5;
// good
var x = y + 5;
```
- End files with a single newline character.
```javascript
// bad
(function(global) {
// ...stuff...
})(this);
```
```javascript
// bad
(function(global) {
// ...stuff...
})(this);↵
↵
```
```javascript
// good
(function(global) {
// ...stuff...
})(this);↵
```
- Use indentation when making long method chains. Use a leading dot, which
emphasizes that the line is a method call, not a new statement.
```javascript
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// bad
$('#items').
find('selected').
highlight().
end().
find('.open').
updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
// bad
var leds = 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);
// good
var leds = 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);
```
- Leave a blank line after blocks and before the next statement
```javascript
// bad
if (foo) {
return bar;
}
return baz;
// good
if (foo) {
return bar;
}
return baz;
// bad
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
// good
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
```
- Magic Numbers and Fancy Stuff should be commented. Magic Numbers are constant values used for calculations. Fancy Stuff are things out of the norm done with good reason.
```javascript
// Magic Numbers
// +10 to move over from border
element.style.left = left + 10 + 'px';
// Fancy Stuff
// parseInt was the reason my code was slow.
// Bitshifting the String to coerce it to a
// Number made it a lot faster.
var val = '10' >> 0;
```
**[⬆ back to top](#table-of-contents)**
## Commas
- Leading commas: **Nope.**
```javascript
// bad
var story = [
once
, upon
, aTime
];
// good
var story = [
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'
];
```
**[⬆ back to top](#table-of-contents)**
## Semicolons
- **Yup.**
```javascript
// bad
(function() {
var name = 'Skywalker'
return name
})()
// good
(function() {
var name = 'Skywalker';
return name;
})();
// good (guards against the function becoming an argument when two files with IIFEs are concatenated)
;(function() {
var name = 'Skywalker';
return name;
})();
```
[Read more](http://stackoverflow.com/a/7365214/1712802).
**[⬆ back to top](#table-of-contents)**
## Type Casting & Coercion
- 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.
```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);
```
- 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), leave a comment explaining why and what you're doing.
```javascript
// 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;
```
- **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
```javascript
2147483647 >> 0 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
```
- Booleans:
```javascript
var age = 0;
// bad
var hasAge = new Boolean(age);
// bad
var hasAge = !!age;
// good
var hasAge = Boolean(age);
// good
var hasAge = age !== undefined;
```
**[⬆ back to top](#table-of-contents)**
## Naming Conventions
- Avoid single letter names and abreviations. Be descriptive with your naming.
```javascript
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
// bad
var perc = 0;
// good
var percentage = 0;
```
- Use camelCase when naming objects, functions, and instances.
```javascript
// 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 PascalCase 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.
```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
```
- Use a leading underscore `_` when naming private methods. Private methods should exist outside of the scope of object and should be invoked using the call method.
```javascript
var dog = {
_name: 'Spot',
bark: function(sound) {
_bark.call( this, sound );
}
};
function _bark(sound) {
console.log(this._name + ':' + sound);
}
  • Boolean variables should prefixed with is or has.

    // badvarcat=false;vareggs=true;// goodvarisCat=false;varhasEggs=true;
  • When saving a reference to this use _this.

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

    // badvarlog=function(msg){console.log(msg);};// goodvarlog=functionlog(msg){console.log(msg);};
  • Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.

⬆ 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;}dragon.age(true);// goodif(!dragon.hasAge()){returnfalse;}drag.setHasAge(true);
  • 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];};
  • Getters and Setters via properties can be used in non processor intensive operations. Should be defined via Object.defineProperty on a prototype

Object.defineProperty(ObjecCar.prototype,'speed',{get: function(){returnthis._speed;},set: function(speed){this._speed=speed;}});

⬆ 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

Events

  • 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});

⬆ back to top

Modules

  • Modules should be built using the CommonJS pattern

    // Creating a module in ./doSomething.jsmodule.exports=functiondoSomething(){console.log('BOO YA!');};
    // Consuming module from ./doSomething.js in another filevardoSomething=require('./doSomething');doSomething();
  • Resuable modules should be distributed on NPM

⬆ back to top

jQuery

  • You should shy away from using jQuery. Instead use modules off NPM like:
    • dom-select
    • dom-style
    • dom-tree
    • dom-event
  • Visit https://github.com/npm-dom for more info.

⬆ back to top

Performance

⬆ back to top

Resources

Read This

Tools

Other Styleguides

Other Styles

Further Reading

Books

Blogs

⬆ back to top

License

(The MIT License)

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

⬆ back to top

};

About

JavaScript Style Guide

Resources

Code of conduct

Contributing

Stars

24 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Experience-Monks/Javascript-Code-Conventions: JavaScript Style Guide · GitHub
Skip to content

Latest commit

History

324 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Jam3 JavaScript Style Guide

Make It Happen and Don't Fuck It Up

Table of Contents

  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. Modules
  21. jQuery
  22. Testing
  23. Performance
  24. Resources
  25. In the Wild
  26. Translation
  27. The JavaScript Style Guide Guide
  28. Chat With Us About Javascript
  29. Contributors
  30. 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={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'};

⬆ back to top

Arrays

  • 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;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;
  • 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 programmatically 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>';}

⬆ back to top

Functions

  • 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.');}}// 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.

    // badvari,len,dragonball,items=getItems(),goSportsTeam=true;// badvari;varitems=getItems();vardragonball;vargoSportsTeam=true;varlen;// goodvaritems=getItems();vargoSportsTeam=true;vardragonball;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;}
  • Do not visually line up variables

    // badvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';// goodvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';

⬆ back to top

Hoisting

  • 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 to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Conditional Expressions & Equality

  • 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 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;// goodif(test)returnfalse;// goodif(test){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}

⬆ back to top

Comments

  • Use /** ... */ to document public function definitions. 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;}
  • Use // for multiline comments when a single line comment is longer than 80 charachters. Or use /* .. */

    // bad// this method will return a fantabulous variable that you can use to do lots of calculations with. If you don't know how to use it see the docs at http://someFakeSite.comvarfantabulousValue=fantabulous();// good// this method will return a fantabulous variable that you can use to do// lots of calculations with. If you don't know how to use it see the docs // at http://someFakeSite.comvarfantabulousValue=fantabulous();// good/* * this method will return a fantabulous variable that you can use to do * lots of calculations with. If you don't know how to use it see the docs  * at http://someFakeSite.com */varfantabulousValue=fantabulous();
  • 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](#table-of-contents)**
## Whitespace
- Use soft tabs set to 2 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'
});
```
- Set off operators with spaces.
```javascript
// bad
var x=y+5;
// good
var x = y + 5;
```
- End files with a single newline character.
```javascript
// bad
(function(global) {
// ...stuff...
})(this);
```
```javascript
// bad
(function(global) {
// ...stuff...
})(this);↵
↵
```
```javascript
// good
(function(global) {
// ...stuff...
})(this);↵
```
- Use indentation when making long method chains. Use a leading dot, which
emphasizes that the line is a method call, not a new statement.
```javascript
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// bad
$('#items').
find('selected').
highlight().
end().
find('.open').
updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
// bad
var leds = 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);
// good
var leds = 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);
```
- Leave a blank line after blocks and before the next statement
```javascript
// bad
if (foo) {
return bar;
}
return baz;
// good
if (foo) {
return bar;
}
return baz;
// bad
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
// good
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
```
- Magic Numbers and Fancy Stuff should be commented. Magic Numbers are constant values used for calculations. Fancy Stuff are things out of the norm done with good reason.
```javascript
// Magic Numbers
// +10 to move over from border
element.style.left = left + 10 + 'px';
// Fancy Stuff
// parseInt was the reason my code was slow.
// Bitshifting the String to coerce it to a
// Number made it a lot faster.
var val = '10' >> 0;
```
**[⬆ back to top](#table-of-contents)**
## Commas
- Leading commas: **Nope.**
```javascript
// bad
var story = [
once
, upon
, aTime
];
// good
var story = [
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'
];
```
**[⬆ back to top](#table-of-contents)**
## Semicolons
- **Yup.**
```javascript
// bad
(function() {
var name = 'Skywalker'
return name
})()
// good
(function() {
var name = 'Skywalker';
return name;
})();
// good (guards against the function becoming an argument when two files with IIFEs are concatenated)
;(function() {
var name = 'Skywalker';
return name;
})();
```
[Read more](http://stackoverflow.com/a/7365214/1712802).
**[⬆ back to top](#table-of-contents)**
## Type Casting & Coercion
- 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.
```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);
```
- 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), leave a comment explaining why and what you're doing.
```javascript
// 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;
```
- **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
```javascript
2147483647 >> 0 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
```
- Booleans:
```javascript
var age = 0;
// bad
var hasAge = new Boolean(age);
// bad
var hasAge = !!age;
// good
var hasAge = Boolean(age);
// good
var hasAge = age !== undefined;
```
**[⬆ back to top](#table-of-contents)**
## Naming Conventions
- Avoid single letter names and abreviations. Be descriptive with your naming.
```javascript
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
// bad
var perc = 0;
// good
var percentage = 0;
```
- Use camelCase when naming objects, functions, and instances.
```javascript
// 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 PascalCase 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.
```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
```
- Use a leading underscore `_` when naming private methods. Private methods should exist outside of the scope of object and should be invoked using the call method.
```javascript
var dog = {
_name: 'Spot',
bark: function(sound) {
_bark.call( this, sound );
}
};
function _bark(sound) {
console.log(this._name + ':' + sound);
}
  • Boolean variables should prefixed with is or has.

    // badvarcat=false;vareggs=true;// goodvarisCat=false;varhasEggs=true;
  • When saving a reference to this use _this.

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

    // badvarlog=function(msg){console.log(msg);};// goodvarlog=functionlog(msg){console.log(msg);};
  • Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.

⬆ 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;}dragon.age(true);// goodif(!dragon.hasAge()){returnfalse;}drag.setHasAge(true);
  • 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];};
  • Getters and Setters via properties can be used in non processor intensive operations. Should be defined via Object.defineProperty on a prototype

Object.defineProperty(ObjecCar.prototype,'speed',{get: function(){returnthis._speed;},set: function(speed){this._speed=speed;}});

⬆ 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

Events

  • 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});

⬆ back to top

Modules

  • Modules should be built using the CommonJS pattern

    // Creating a module in ./doSomething.jsmodule.exports=functiondoSomething(){console.log('BOO YA!');};
    // Consuming module from ./doSomething.js in another filevardoSomething=require('./doSomething');doSomething();
  • Resuable modules should be distributed on NPM

⬆ back to top

jQuery

  • You should shy away from using jQuery. Instead use modules off NPM like:
    • dom-select
    • dom-style
    • dom-tree
    • dom-event
  • Visit https://github.com/npm-dom for more info.

⬆ back to top

Performance

⬆ back to top

Resources

Read This

Tools

Other Styleguides

Other Styles

Further Reading

Books

Blogs

⬆ back to top

License

(The MIT License)

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

⬆ back to top

};

About

JavaScript Style Guide

Resources

Code of conduct

Contributing

Stars

24 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - Experience-Monks/Javascript-Code-Conventions: JavaScript Style Guide · GitHub
Skip to content

Latest commit

History

324 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Jam3 JavaScript Style Guide

Make It Happen and Don't Fuck It Up

Table of Contents

  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. Modules
  21. jQuery
  22. Testing
  23. Performance
  24. Resources
  25. In the Wild
  26. Translation
  27. The JavaScript Style Guide Guide
  28. Chat With Us About Javascript
  29. Contributors
  30. 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={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'};

⬆ back to top

Arrays

  • 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;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;
  • 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 programmatically 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>';}

⬆ back to top

Functions

  • 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.');}}// 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.

    // badvari,len,dragonball,items=getItems(),goSportsTeam=true;// badvari;varitems=getItems();vardragonball;vargoSportsTeam=true;varlen;// goodvaritems=getItems();vargoSportsTeam=true;vardragonball;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;}
  • Do not visually line up variables

    // badvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';// goodvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';

⬆ back to top

Hoisting

  • 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 to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Conditional Expressions & Equality

  • 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 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;// goodif(test)returnfalse;// goodif(test){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}

⬆ back to top

Comments

  • Use /** ... */ to document public function definitions. 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;}
  • Use // for multiline comments when a single line comment is longer than 80 charachters. Or use /* .. */

    // bad// this method will return a fantabulous variable that you can use to do lots of calculations with. If you don't know how to use it see the docs at http://someFakeSite.comvarfantabulousValue=fantabulous();// good// this method will return a fantabulous variable that you can use to do// lots of calculations with. If you don't know how to use it see the docs // at http://someFakeSite.comvarfantabulousValue=fantabulous();// good/* * this method will return a fantabulous variable that you can use to do * lots of calculations with. If you don't know how to use it see the docs  * at http://someFakeSite.com */varfantabulousValue=fantabulous();
  • 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](#table-of-contents)**
## Whitespace
- Use soft tabs set to 2 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'
});
```
- Set off operators with spaces.
```javascript
// bad
var x=y+5;
// good
var x = y + 5;
```
- End files with a single newline character.
```javascript
// bad
(function(global) {
// ...stuff...
})(this);
```
```javascript
// bad
(function(global) {
// ...stuff...
})(this);↵
↵
```
```javascript
// good
(function(global) {
// ...stuff...
})(this);↵
```
- Use indentation when making long method chains. Use a leading dot, which
emphasizes that the line is a method call, not a new statement.
```javascript
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// bad
$('#items').
find('selected').
highlight().
end().
find('.open').
updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
// bad
var leds = 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);
// good
var leds = 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);
```
- Leave a blank line after blocks and before the next statement
```javascript
// bad
if (foo) {
return bar;
}
return baz;
// good
if (foo) {
return bar;
}
return baz;
// bad
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
// good
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
```
- Magic Numbers and Fancy Stuff should be commented. Magic Numbers are constant values used for calculations. Fancy Stuff are things out of the norm done with good reason.
```javascript
// Magic Numbers
// +10 to move over from border
element.style.left = left + 10 + 'px';
// Fancy Stuff
// parseInt was the reason my code was slow.
// Bitshifting the String to coerce it to a
// Number made it a lot faster.
var val = '10' >> 0;
```
**[⬆ back to top](#table-of-contents)**
## Commas
- Leading commas: **Nope.**
```javascript
// bad
var story = [
once
, upon
, aTime
];
// good
var story = [
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'
];
```
**[⬆ back to top](#table-of-contents)**
## Semicolons
- **Yup.**
```javascript
// bad
(function() {
var name = 'Skywalker'
return name
})()
// good
(function() {
var name = 'Skywalker';
return name;
})();
// good (guards against the function becoming an argument when two files with IIFEs are concatenated)
;(function() {
var name = 'Skywalker';
return name;
})();
```
[Read more](http://stackoverflow.com/a/7365214/1712802).
**[⬆ back to top](#table-of-contents)**
## Type Casting & Coercion
- 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.
```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);
```
- 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), leave a comment explaining why and what you're doing.
```javascript
// 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;
```
- **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
```javascript
2147483647 >> 0 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
```
- Booleans:
```javascript
var age = 0;
// bad
var hasAge = new Boolean(age);
// bad
var hasAge = !!age;
// good
var hasAge = Boolean(age);
// good
var hasAge = age !== undefined;
```
**[⬆ back to top](#table-of-contents)**
## Naming Conventions
- Avoid single letter names and abreviations. Be descriptive with your naming.
```javascript
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
// bad
var perc = 0;
// good
var percentage = 0;
```
- Use camelCase when naming objects, functions, and instances.
```javascript
// 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 PascalCase 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.
```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
```
- Use a leading underscore `_` when naming private methods. Private methods should exist outside of the scope of object and should be invoked using the call method.
```javascript
var dog = {
_name: 'Spot',
bark: function(sound) {
_bark.call( this, sound );
}
};
function _bark(sound) {
console.log(this._name + ':' + sound);
}
  • Boolean variables should prefixed with is or has.

    // badvarcat=false;vareggs=true;// goodvarisCat=false;varhasEggs=true;
  • When saving a reference to this use _this.

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

    // badvarlog=function(msg){console.log(msg);};// goodvarlog=functionlog(msg){console.log(msg);};
  • Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.

⬆ 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;}dragon.age(true);// goodif(!dragon.hasAge()){returnfalse;}drag.setHasAge(true);
  • 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];};
  • Getters and Setters via properties can be used in non processor intensive operations. Should be defined via Object.defineProperty on a prototype

Object.defineProperty(ObjecCar.prototype,'speed',{get: function(){returnthis._speed;},set: function(speed){this._speed=speed;}});

⬆ 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

Events

  • 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});

⬆ back to top

Modules

  • Modules should be built using the CommonJS pattern

    // Creating a module in ./doSomething.jsmodule.exports=functiondoSomething(){console.log('BOO YA!');};
    // Consuming module from ./doSomething.js in another filevardoSomething=require('./doSomething');doSomething();
  • Resuable modules should be distributed on NPM

⬆ back to top

jQuery

  • You should shy away from using jQuery. Instead use modules off NPM like:
    • dom-select
    • dom-style
    • dom-tree
    • dom-event
  • Visit https://github.com/npm-dom for more info.

⬆ back to top

Performance

⬆ back to top

Resources

Read This

Tools

Other Styleguides

Other Styles

Further Reading

Books

Blogs

⬆ back to top

License

(The MIT License)

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

⬆ back to top

};

About

JavaScript Style Guide

Resources

Code of conduct

Contributing

Stars

24 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Experience-Monks/Javascript-Code-Conventions: JavaScript Style Guide · GitHub
Skip to content

Latest commit

History

324 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Jam3 JavaScript Style Guide

Make It Happen and Don't Fuck It Up

Table of Contents

  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. Modules
  21. jQuery
  22. Testing
  23. Performance
  24. Resources
  25. In the Wild
  26. Translation
  27. The JavaScript Style Guide Guide
  28. Chat With Us About Javascript
  29. Contributors
  30. 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={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'};

⬆ back to top

Arrays

  • 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;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;
  • 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 programmatically 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>';}

⬆ back to top

Functions

  • 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.');}}// 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.

    // badvari,len,dragonball,items=getItems(),goSportsTeam=true;// badvari;varitems=getItems();vardragonball;vargoSportsTeam=true;varlen;// goodvaritems=getItems();vargoSportsTeam=true;vardragonball;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;}
  • Do not visually line up variables

    // badvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';// goodvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';

⬆ back to top

Hoisting

  • 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 to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Conditional Expressions & Equality

  • 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 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;// goodif(test)returnfalse;// goodif(test){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}

⬆ back to top

Comments

  • Use /** ... */ to document public function definitions. 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;}
  • Use // for multiline comments when a single line comment is longer than 80 charachters. Or use /* .. */

    // bad// this method will return a fantabulous variable that you can use to do lots of calculations with. If you don't know how to use it see the docs at http://someFakeSite.comvarfantabulousValue=fantabulous();// good// this method will return a fantabulous variable that you can use to do// lots of calculations with. If you don't know how to use it see the docs // at http://someFakeSite.comvarfantabulousValue=fantabulous();// good/* * this method will return a fantabulous variable that you can use to do * lots of calculations with. If you don't know how to use it see the docs  * at http://someFakeSite.com */varfantabulousValue=fantabulous();
  • 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](#table-of-contents)**
## Whitespace
- Use soft tabs set to 2 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'
});
```
- Set off operators with spaces.
```javascript
// bad
var x=y+5;
// good
var x = y + 5;
```
- End files with a single newline character.
```javascript
// bad
(function(global) {
// ...stuff...
})(this);
```
```javascript
// bad
(function(global) {
// ...stuff...
})(this);↵
↵
```
```javascript
// good
(function(global) {
// ...stuff...
})(this);↵
```
- Use indentation when making long method chains. Use a leading dot, which
emphasizes that the line is a method call, not a new statement.
```javascript
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// bad
$('#items').
find('selected').
highlight().
end().
find('.open').
updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
// bad
var leds = 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);
// good
var leds = 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);
```
- Leave a blank line after blocks and before the next statement
```javascript
// bad
if (foo) {
return bar;
}
return baz;
// good
if (foo) {
return bar;
}
return baz;
// bad
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
// good
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
```
- Magic Numbers and Fancy Stuff should be commented. Magic Numbers are constant values used for calculations. Fancy Stuff are things out of the norm done with good reason.
```javascript
// Magic Numbers
// +10 to move over from border
element.style.left = left + 10 + 'px';
// Fancy Stuff
// parseInt was the reason my code was slow.
// Bitshifting the String to coerce it to a
// Number made it a lot faster.
var val = '10' >> 0;
```
**[⬆ back to top](#table-of-contents)**
## Commas
- Leading commas: **Nope.**
```javascript
// bad
var story = [
once
, upon
, aTime
];
// good
var story = [
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'
];
```
**[⬆ back to top](#table-of-contents)**
## Semicolons
- **Yup.**
```javascript
// bad
(function() {
var name = 'Skywalker'
return name
})()
// good
(function() {
var name = 'Skywalker';
return name;
})();
// good (guards against the function becoming an argument when two files with IIFEs are concatenated)
;(function() {
var name = 'Skywalker';
return name;
})();
```
[Read more](http://stackoverflow.com/a/7365214/1712802).
**[⬆ back to top](#table-of-contents)**
## Type Casting & Coercion
- 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.
```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);
```
- 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), leave a comment explaining why and what you're doing.
```javascript
// 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;
```
- **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
```javascript
2147483647 >> 0 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
```
- Booleans:
```javascript
var age = 0;
// bad
var hasAge = new Boolean(age);
// bad
var hasAge = !!age;
// good
var hasAge = Boolean(age);
// good
var hasAge = age !== undefined;
```
**[⬆ back to top](#table-of-contents)**
## Naming Conventions
- Avoid single letter names and abreviations. Be descriptive with your naming.
```javascript
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
// bad
var perc = 0;
// good
var percentage = 0;
```
- Use camelCase when naming objects, functions, and instances.
```javascript
// 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 PascalCase 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.
```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
```
- Use a leading underscore `_` when naming private methods. Private methods should exist outside of the scope of object and should be invoked using the call method.
```javascript
var dog = {
_name: 'Spot',
bark: function(sound) {
_bark.call( this, sound );
}
};
function _bark(sound) {
console.log(this._name + ':' + sound);
}
  • Boolean variables should prefixed with is or has.

    // badvarcat=false;vareggs=true;// goodvarisCat=false;varhasEggs=true;
  • When saving a reference to this use _this.

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

    // badvarlog=function(msg){console.log(msg);};// goodvarlog=functionlog(msg){console.log(msg);};
  • Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.

⬆ 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;}dragon.age(true);// goodif(!dragon.hasAge()){returnfalse;}drag.setHasAge(true);
  • 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];};
  • Getters and Setters via properties can be used in non processor intensive operations. Should be defined via Object.defineProperty on a prototype

Object.defineProperty(ObjecCar.prototype,'speed',{get: function(){returnthis._speed;},set: function(speed){this._speed=speed;}});

⬆ 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

Events

  • 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});

⬆ back to top

Modules

  • Modules should be built using the CommonJS pattern

    // Creating a module in ./doSomething.jsmodule.exports=functiondoSomething(){console.log('BOO YA!');};
    // Consuming module from ./doSomething.js in another filevardoSomething=require('./doSomething');doSomething();
  • Resuable modules should be distributed on NPM

⬆ back to top

jQuery

  • You should shy away from using jQuery. Instead use modules off NPM like:
    • dom-select
    • dom-style
    • dom-tree
    • dom-event
  • Visit https://github.com/npm-dom for more info.

⬆ back to top

Performance

⬆ back to top

Resources

Read This

Tools

Other Styleguides

Other Styles

Further Reading

Books

Blogs

⬆ back to top

License

(The MIT License)

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

⬆ back to top

};

About

JavaScript Style Guide

Resources

Code of conduct

Contributing

Stars

24 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - Experience-Monks/Javascript-Code-Conventions: JavaScript Style Guide · GitHub
Skip to content

Latest commit

History

324 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Jam3 JavaScript Style Guide

Make It Happen and Don't Fuck It Up

Table of Contents

  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. Modules
  21. jQuery
  22. Testing
  23. Performance
  24. Resources
  25. In the Wild
  26. Translation
  27. The JavaScript Style Guide Guide
  28. Chat With Us About Javascript
  29. Contributors
  30. 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={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'};

⬆ back to top

Arrays

  • 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;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;
  • 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 programmatically 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>';}

⬆ back to top

Functions

  • 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.');}}// 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.

    // badvari,len,dragonball,items=getItems(),goSportsTeam=true;// badvari;varitems=getItems();vardragonball;vargoSportsTeam=true;varlen;// goodvaritems=getItems();vargoSportsTeam=true;vardragonball;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;}
  • Do not visually line up variables

    // badvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';// goodvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';

⬆ back to top

Hoisting

  • 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 to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Conditional Expressions & Equality

  • 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 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;// goodif(test)returnfalse;// goodif(test){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}

⬆ back to top

Comments

  • Use /** ... */ to document public function definitions. 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;}
  • Use // for multiline comments when a single line comment is longer than 80 charachters. Or use /* .. */

    // bad// this method will return a fantabulous variable that you can use to do lots of calculations with. If you don't know how to use it see the docs at http://someFakeSite.comvarfantabulousValue=fantabulous();// good// this method will return a fantabulous variable that you can use to do// lots of calculations with. If you don't know how to use it see the docs // at http://someFakeSite.comvarfantabulousValue=fantabulous();// good/* * this method will return a fantabulous variable that you can use to do * lots of calculations with. If you don't know how to use it see the docs  * at http://someFakeSite.com */varfantabulousValue=fantabulous();
  • 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](#table-of-contents)**
## Whitespace
- Use soft tabs set to 2 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'
});
```
- Set off operators with spaces.
```javascript
// bad
var x=y+5;
// good
var x = y + 5;
```
- End files with a single newline character.
```javascript
// bad
(function(global) {
// ...stuff...
})(this);
```
```javascript
// bad
(function(global) {
// ...stuff...
})(this);↵
↵
```
```javascript
// good
(function(global) {
// ...stuff...
})(this);↵
```
- Use indentation when making long method chains. Use a leading dot, which
emphasizes that the line is a method call, not a new statement.
```javascript
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// bad
$('#items').
find('selected').
highlight().
end().
find('.open').
updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
// bad
var leds = 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);
// good
var leds = 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);
```
- Leave a blank line after blocks and before the next statement
```javascript
// bad
if (foo) {
return bar;
}
return baz;
// good
if (foo) {
return bar;
}
return baz;
// bad
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
// good
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
```
- Magic Numbers and Fancy Stuff should be commented. Magic Numbers are constant values used for calculations. Fancy Stuff are things out of the norm done with good reason.
```javascript
// Magic Numbers
// +10 to move over from border
element.style.left = left + 10 + 'px';
// Fancy Stuff
// parseInt was the reason my code was slow.
// Bitshifting the String to coerce it to a
// Number made it a lot faster.
var val = '10' >> 0;
```
**[⬆ back to top](#table-of-contents)**
## Commas
- Leading commas: **Nope.**
```javascript
// bad
var story = [
once
, upon
, aTime
];
// good
var story = [
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'
];
```
**[⬆ back to top](#table-of-contents)**
## Semicolons
- **Yup.**
```javascript
// bad
(function() {
var name = 'Skywalker'
return name
})()
// good
(function() {
var name = 'Skywalker';
return name;
})();
// good (guards against the function becoming an argument when two files with IIFEs are concatenated)
;(function() {
var name = 'Skywalker';
return name;
})();
```
[Read more](http://stackoverflow.com/a/7365214/1712802).
**[⬆ back to top](#table-of-contents)**
## Type Casting & Coercion
- 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.
```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);
```
- 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), leave a comment explaining why and what you're doing.
```javascript
// 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;
```
- **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
```javascript
2147483647 >> 0 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
```
- Booleans:
```javascript
var age = 0;
// bad
var hasAge = new Boolean(age);
// bad
var hasAge = !!age;
// good
var hasAge = Boolean(age);
// good
var hasAge = age !== undefined;
```
**[⬆ back to top](#table-of-contents)**
## Naming Conventions
- Avoid single letter names and abreviations. Be descriptive with your naming.
```javascript
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
// bad
var perc = 0;
// good
var percentage = 0;
```
- Use camelCase when naming objects, functions, and instances.
```javascript
// 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 PascalCase 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.
```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
```
- Use a leading underscore `_` when naming private methods. Private methods should exist outside of the scope of object and should be invoked using the call method.
```javascript
var dog = {
_name: 'Spot',
bark: function(sound) {
_bark.call( this, sound );
}
};
function _bark(sound) {
console.log(this._name + ':' + sound);
}
  • Boolean variables should prefixed with is or has.

    // badvarcat=false;vareggs=true;// goodvarisCat=false;varhasEggs=true;
  • When saving a reference to this use _this.

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

    // badvarlog=function(msg){console.log(msg);};// goodvarlog=functionlog(msg){console.log(msg);};
  • Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.

⬆ 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;}dragon.age(true);// goodif(!dragon.hasAge()){returnfalse;}drag.setHasAge(true);
  • 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];};
  • Getters and Setters via properties can be used in non processor intensive operations. Should be defined via Object.defineProperty on a prototype

Object.defineProperty(ObjecCar.prototype,'speed',{get: function(){returnthis._speed;},set: function(speed){this._speed=speed;}});

⬆ 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

Events

  • 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});

⬆ back to top

Modules

  • Modules should be built using the CommonJS pattern

    // Creating a module in ./doSomething.jsmodule.exports=functiondoSomething(){console.log('BOO YA!');};
    // Consuming module from ./doSomething.js in another filevardoSomething=require('./doSomething');doSomething();
  • Resuable modules should be distributed on NPM

⬆ back to top

jQuery

  • You should shy away from using jQuery. Instead use modules off NPM like:
    • dom-select
    • dom-style
    • dom-tree
    • dom-event
  • Visit https://github.com/npm-dom for more info.

⬆ back to top

Performance

⬆ back to top

Resources

Read This

Tools

Other Styleguides

Other Styles

Further Reading

Books

Blogs

⬆ back to top

License

(The MIT License)

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

⬆ back to top

};

About

JavaScript Style Guide

Resources

Code of conduct

Contributing

Stars

24 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - Experience-Monks/Javascript-Code-Conventions: JavaScript Style Guide · GitHub
Skip to content

Latest commit

History

324 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Jam3 JavaScript Style Guide

Make It Happen and Don't Fuck It Up

Table of Contents

  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. Modules
  21. jQuery
  22. Testing
  23. Performance
  24. Resources
  25. In the Wild
  26. Translation
  27. The JavaScript Style Guide Guide
  28. Chat With Us About Javascript
  29. Contributors
  30. 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={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'};

⬆ back to top

Arrays

  • 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;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;
  • 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 programmatically 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>';}

⬆ back to top

Functions

  • 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.');}}// 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.

    // badvari,len,dragonball,items=getItems(),goSportsTeam=true;// badvari;varitems=getItems();vardragonball;vargoSportsTeam=true;varlen;// goodvaritems=getItems();vargoSportsTeam=true;vardragonball;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;}
  • Do not visually line up variables

    // badvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';// goodvarname='Name';varlongerName='Longer Name';varevenLongerName='Even Longer Name';

⬆ back to top

Hoisting

  • 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 to JavaScript Scoping & Hoisting by Ben Cherry.

⬆ back to top

Conditional Expressions & Equality

  • 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 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;// goodif(test)returnfalse;// goodif(test){returnfalse;}// badfunction(){returnfalse;}// goodfunction(){returnfalse;}

⬆ back to top

Comments

  • Use /** ... */ to document public function definitions. 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;}
  • Use // for multiline comments when a single line comment is longer than 80 charachters. Or use /* .. */

    // bad// this method will return a fantabulous variable that you can use to do lots of calculations with. If you don't know how to use it see the docs at http://someFakeSite.comvarfantabulousValue=fantabulous();// good// this method will return a fantabulous variable that you can use to do// lots of calculations with. If you don't know how to use it see the docs // at http://someFakeSite.comvarfantabulousValue=fantabulous();// good/* * this method will return a fantabulous variable that you can use to do * lots of calculations with. If you don't know how to use it see the docs  * at http://someFakeSite.com */varfantabulousValue=fantabulous();
  • 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](#table-of-contents)**
## Whitespace
- Use soft tabs set to 2 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'
});
```
- Set off operators with spaces.
```javascript
// bad
var x=y+5;
// good
var x = y + 5;
```
- End files with a single newline character.
```javascript
// bad
(function(global) {
// ...stuff...
})(this);
```
```javascript
// bad
(function(global) {
// ...stuff...
})(this);↵
↵
```
```javascript
// good
(function(global) {
// ...stuff...
})(this);↵
```
- Use indentation when making long method chains. Use a leading dot, which
emphasizes that the line is a method call, not a new statement.
```javascript
// bad
$('#items').find('.selected').highlight().end().find('.open').updateCount();
// bad
$('#items').
find('selected').
highlight().
end().
find('.open').
updateCount();
// good
$('#items')
.find('.selected')
.highlight()
.end()
.find('.open')
.updateCount();
// bad
var leds = 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);
// good
var leds = 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);
```
- Leave a blank line after blocks and before the next statement
```javascript
// bad
if (foo) {
return bar;
}
return baz;
// good
if (foo) {
return bar;
}
return baz;
// bad
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
// good
var obj = {
foo: function() {
},
bar: function() {
}
};
return obj;
```
- Magic Numbers and Fancy Stuff should be commented. Magic Numbers are constant values used for calculations. Fancy Stuff are things out of the norm done with good reason.
```javascript
// Magic Numbers
// +10 to move over from border
element.style.left = left + 10 + 'px';
// Fancy Stuff
// parseInt was the reason my code was slow.
// Bitshifting the String to coerce it to a
// Number made it a lot faster.
var val = '10' >> 0;
```
**[⬆ back to top](#table-of-contents)**
## Commas
- Leading commas: **Nope.**
```javascript
// bad
var story = [
once
, upon
, aTime
];
// good
var story = [
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'
];
```
**[⬆ back to top](#table-of-contents)**
## Semicolons
- **Yup.**
```javascript
// bad
(function() {
var name = 'Skywalker'
return name
})()
// good
(function() {
var name = 'Skywalker';
return name;
})();
// good (guards against the function becoming an argument when two files with IIFEs are concatenated)
;(function() {
var name = 'Skywalker';
return name;
})();
```
[Read more](http://stackoverflow.com/a/7365214/1712802).
**[⬆ back to top](#table-of-contents)**
## Type Casting & Coercion
- 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.
```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);
```
- 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), leave a comment explaining why and what you're doing.
```javascript
// 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;
```
- **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](http://es5.github.io/#x4.3.19), but Bitshift operations always return a 32-bit integer ([source](http://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
```javascript
2147483647 >> 0 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
```
- Booleans:
```javascript
var age = 0;
// bad
var hasAge = new Boolean(age);
// bad
var hasAge = !!age;
// good
var hasAge = Boolean(age);
// good
var hasAge = age !== undefined;
```
**[⬆ back to top](#table-of-contents)**
## Naming Conventions
- Avoid single letter names and abreviations. Be descriptive with your naming.
```javascript
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
// bad
var perc = 0;
// good
var percentage = 0;
```
- Use camelCase when naming objects, functions, and instances.
```javascript
// 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 PascalCase 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.
```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
```
- Use a leading underscore `_` when naming private methods. Private methods should exist outside of the scope of object and should be invoked using the call method.
```javascript
var dog = {
_name: 'Spot',
bark: function(sound) {
_bark.call( this, sound );
}
};
function _bark(sound) {
console.log(this._name + ':' + sound);
}
  • Boolean variables should prefixed with is or has.

    // badvarcat=false;vareggs=true;// goodvarisCat=false;varhasEggs=true;
  • When saving a reference to this use _this.

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

    // badvarlog=function(msg){console.log(msg);};// goodvarlog=functionlog(msg){console.log(msg);};
  • Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.

⬆ 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;}dragon.age(true);// goodif(!dragon.hasAge()){returnfalse;}drag.setHasAge(true);
  • 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];};
  • Getters and Setters via properties can be used in non processor intensive operations. Should be defined via Object.defineProperty on a prototype

Object.defineProperty(ObjecCar.prototype,'speed',{get: function(){returnthis._speed;},set: function(speed){this._speed=speed;}});

⬆ 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

Events

  • 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});

⬆ back to top

Modules

  • Modules should be built using the CommonJS pattern

    // Creating a module in ./doSomething.jsmodule.exports=functiondoSomething(){console.log('BOO YA!');};
    // Consuming module from ./doSomething.js in another filevardoSomething=require('./doSomething');doSomething();
  • Resuable modules should be distributed on NPM

⬆ back to top

jQuery

  • You should shy away from using jQuery. Instead use modules off NPM like:
    • dom-select
    • dom-style
    • dom-tree
    • dom-event
  • Visit https://github.com/npm-dom for more info.

⬆ back to top

Performance

⬆ back to top

Resources

Read This

Tools

Other Styleguides

Other Styles

Further Reading

Books

Blogs

⬆ back to top

License

(The MIT License)

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

⬆ back to top

};

About

JavaScript Style Guide

Resources

Code of conduct

Contributing

Stars

24 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages