Home

Awesome

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

⬆ back to top

Objects

⬆ back to top

Arrays

⬆ back to top

Strings

⬆ back to top

Functions

⬆ back to top

Properties

⬆ back to top

Variables

⬆ back to top

Hoisting

⬆ back to top

Conditional Expressions & Equality

⬆ back to top

Blocks

⬆ back to top

Comments


**[⬆ 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);
}

⬆ back to top

Accessors

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

  set: function(speed) {
    this._speed = speed;
  }
});

⬆ back to top

Constructors

⬆ back to top

Events

⬆ back to top

Modules

⬆ back to top

jQuery

⬆ 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

};