Procur JavaScript Style Guide

###All code in any code-base should look like a single person typed it, no matter how many people contributed.### ###As a general rule of thumb, don't do stupid shit and everything will be ok.###

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. Danger Zone
  22. Testing
  23. Resources

Types

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

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

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

⬆ back to top

Objects

  • Use the literal syntax for object creation.

    // bad
    var item = new Object();
    
    // good
    var item = {};
  • Don't use reserved words as keys. It won't work in IE8. More info

    // bad
    var superman = {
      default: { clark: 'kent' },
      private: true
    };
    
    // good
    var superman = {
      defaults: { clark: 'kent' },
      hidden: true
    };
  • In instances where a reserved word must be used, for example catch, which is often a method on Promise objects, use subscript notation

  • Note: this approach must only be followed when the code will run on the browser where IE8 compatability may be a concern

    // bad
    asyncCall()
      .then(doSomething)
      .then(doSomethingElse)
      .catch(handleError);
    
    // good
    asyncCall()
      .then(doSomething)
      .then(doSomethingElse)
      ['catch'](handleError);
  • Use readable synonyms in place of reserved words.

    // bad
    var superman = {
      class: 'alien'
    };
    
    // bad
    var superman = {
      klass: 'alien'
    };
    
    // good
    var superman = {
      type: 'alien'
    };

⬆ back to top

Arrays

  • Use the literal syntax for array creation

    // bad
    var items = new Array();
    
    // good
    var items = [];
  • If you don't know an array's length use Array#push.

    var someStack = [];
    
    
    // bad
    someStack[someStack.length] = 'abracadabra';
    
    // good
    someStack.push('abracadabra');

⬆ back to top

Strings

  • Use single quotes '' for strings

    // bad
    var name = "Clark Kent";
    
    // good
    var name = 'Clark Kent';
    
    // bad
    var fullName = "Clark " + this.lastName;
    
    // good
    var fullName = 'Clark ' + 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

    // bad
    var errorMessage = '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.';
    
    // bad
    var errorMessage = '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.';
    
    // good
    var errorMessage = '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.';

Functions

  • Function expressions:

    // anonymous function expression
    var anonymous = function() {
      return true;
    };
    
    // named function expression
    var named = function named() {
      return true;
    };
    
    // immediately-invoked function expression (IIFE)
    (function() {
      console.log('Welcome to the Internet. Please follow me.');
    })();
  • Function declaration:

    function declaredName() {
      return true;
    }
  • Keep function definitions in callbacks within the argument list to a minimum, particularly for large, complex functions. Instead use a named function declaration and pass the name reference.

    // bad
    asyncCall(foo, function(err, result) {
      // ...stuff...
      // ...more stuff...
      // ...lots of stuff...
    });
    
    // okay - small function
    asyncCall(foo, function handlResponse(err, result) {
      return result.data;
    });
    
    // good
    asyncCall(foo, handleResponse);
    
    function handleResponse(err, result) {
      // ...stuff...
      // ...more stuff...
      // ...lots of stuff...
    }
  • Unless an IIFE is being used to create a closure or scope, all functions should be named via the function declaration syntax. Anonymous functions will display as such in the error call stack, so naming a function will provide better error reporting. Function declarations get hoisted, so they can be accessed from anywhere within the lexical scope, even above their definition (see Hoisting for more information).

  • Never declare a function in a non-function block (if, while, etc).

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

    // bad
    if (currentUser) {
      function test() {
        console.log('Nope.');
      }
    }
    
    // good
    if (currentUser) {
      // ...stuff...
    }
    
    function test() {
      console.log('Yup.');
    }
  • Never name a parameter arguments, this will take precedence over the arguments object that is given to every function scope.

  • Give paramaters meaningful names over abstract ones (see Naming Conventions).

    // bad
    function nope(name, options, arguments) {
      // ...stuff...
    }
    
    // good
    function yup(name, options, args) {
      // ...stuff...
    }
    
    // best
    function yup(name, options, config) {
      // ...stuff...
    }
  • The return value must be on the same line as the return keyword in order to avoid semicolon insertion.

    // bad
    function foo() {
      return
        'bar';
    }
    
    foo() // => undefined
    
    // good
    function foo() {
      return 'bar';
    }
    
    foo() // => 'bar'

⬆ back to top

Properties

  • Use dot notation when accessing properties.

    var luke = {
      jedi: true,
      age: 28
    };
    
    // bad
    var isJedi = luke['jedi'];
    
    // good
    var isJedi = luke.jedi;
  • Use subscript notation [] when accessing properties with a variable (or when a reserved word must be used -- see the Objects section).

    var luke = {
      jedi: true,
      age: 28
    };
    
    function getProp(prop) {
      return luke[prop];
    }
    
    var isJedi = 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.

    // bad
    superPower = new SuperPower();
    
    // good
    var superPower = new SuperPower();
  • Use one var declaration for multiple variables within the same scope and declare each variable on a newline.

    // bad
    var items = getItems();
    var goSportsTeam = true;
    var dragonball = 'z';
    
    // good
    var
      items = getItems(),
      goSportsTeam = true,
      dragonball = 'z';
  • Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.

    // bad
    var
      i,
      len,
      dragonball,
      items = getItems(),
      goSportsTeam = true;
    
    // bad
    var
      i,
      items = getItems(),
      dragonball,
      goSportsTeam = true,
      len;
    
    // good
    var
      items = getItems(),
      goSportsTeam = true,
      dragonball,
      length,
      i;
  • Avoid large variable assignments when declaring multiple variables.

    // bad
    var
      superHeroes = {
        superman: 'Clark Kent',
        bathman: 'Bruce Wayne',
        greenLantern: 'Hal Jordan',
        ironman: 'Tony Stark'
      },
      superVillains = [
        'Lex Luther',
        'Joker',
        'Sinestro',
        'Mandarin'
      ];
    
    // good
    var
      superHeroes,
      superVillains;
    
    superHeroes = {
      superman: 'Clark Kent',
      bathman: 'Bruce Wayne',
      greenLantern: 'Hal Jordan',
      ironman: 'Tony Stark'
    };
    
    superVillains = [
      'Lex Luther',
      'Joker',
      'Sinestro',
      'Mandarin'
    ];
  • Assign variables at the top of their scope (if you have variables, the var statement should be the first statement in the function body). This helps avoid issues with variable declaration and assignment hoisting related issues.

    // bad
    function() {
      test();
      console.log('doing stuff..');
    
      //..other stuff..
    
      var name = getName();
    
      if (name === 'test') {
        return false;
      }
    
      return name;
    }
    
    // good
    function() {
      var name = getName();
    
      test();
      console.log('doing stuff..');
    
      //..other stuff..
    
      if (name === 'test') {
        return false;
      }
    
      return name;
    }
    
    // bad
    function() {
      var name = getName();
    
      if (!arguments.length) {
        return false;
      }
    
      return true;
    }
    
    // good
    function() {
      var name;
    
      if (!arguments.length) {
        return false;
      }
    
      name = getName();
    
      return true;
    }
  • const and let, from ES6, should also be assigned at the top of their block scope

    // bad
    function foo() {
      let
        foo,
        bar;
      if (condition) {
        bar = 'baz';
        // statements
      }
    }
    
    // good
    function foo() {
      let foo;
      if (condition) {
        let bar = 'baz';
        // statements
      }
    }

⬆ 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)
    function example() {
      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.
    function example() {
      console.log(declaredButNotAssigned); // => undefined
      var declaredButNotAssigned = true;
    }
    
    // The interpreter is hoisting the variable
    // declaration to the top of the scope.
    // Which means our example could be rewritten as:
    function example() {
      var declaredButNotAssigned;
      console.log(declaredButNotAssigned); // => undefined
      declaredButNotAssigned = true;
    }
  • Anonymous function expressions hoist their variable name, but not the function assignment.

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

    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      superPower(); // => ReferenceError superPower is not defined
    
      var named = function superPower() {
        console.log('Flying');
      };
    }
    
    // the same is true when the function name
    // is the same as the variable name.
    function example() {
      console.log(named); // => undefined
    
      named(); // => TypeError named is not a function
    
      var named = function named() {
        console.log('named');
      }
    }
  • Function declarations hoist their name and the function body.

    function example() {
      superPower(); // => Flying
    
      function superPower() {
        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
    }
  • Avoid doing assignments as part of a conditional.

    // bad
    if (a = b) {
      // ...stuff...
    }
    
    // good
    a = b;
    
    if (a) {
      // ...stuff...
    }
  • Use shortcuts.

    // Strings
    // bad
    if (name !== '') {
      // ...stuff...
    }
    
    if (otherName === '') {
      // ...stuff...
    }
    
    // good
    if (name) {
      // ...stuff...
    }
    
    if (!otherName) {
      // ...stuff...
    }
    
    // Booleans
    // bad
    if (foo === true) {
      // ...stuff...
    }
    
    if (bar === false) {
      // ...stuff...
    }
    
    // good
    if (foo) {
      // ...stuff...
    }
    
    if (!bar) {
      // ...stuff...
    }
    
    // Array Length
    // bad
    if (collection.length > 0) {
      // ...stuff...
    }
    
    if (otherCollection.length === 0) {
      // ...stuff...
    }
    
    // good
    if (collection.length) {
      // ...stuff...
    }
    
    if (!otherCollection.length) {
      // ...stuff...
    }
    
    // Null and Undefined
    // When only evaluating a ref that might be null or undefined, but NOT false, "" or 0,
    if (foo === null || foo === undefined) {
      // ...stuff...
    }
  • For more information see Truth Equality and JavaScript by Angus Croll

⬆ back to top

Blocks

  • Use braces with all multi-line blocks.

    // bad
    if (test)
      return false;
    
    // good
    if (test) return false;
    
    // best
    if (test) {
      return false;
    }
    
    // okay
    function() { return false; }
    
    // good
    function() {
      return false;
    }

⬆ back to top

Comments

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

    // bad
    // make() returns a new element
    // based on the passed in tag name
    function make(tag) {
    
      // ...stuff...
    
      return element;
    }
    
    // good
    /**
     * make() returns a new element
     * based on the passed in tag name
     */
    function make(tag) {
    
      // ...stuff...
    
      return element;
    }
  • 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.

    // bad
    var active = true;  // is current tab
    
    // good
    // is current tab
    var active = true;
    
    // bad
    function getType() {
      console.log('fetching type...');
      // set the default type to 'no type'
      var type = this._type || 'no type';
    
      return type;
    }
    
    // good
    function getType() {
      console.log('fetching type...');
    
      // set the default type to 'no type'
      var type = this._type || 'no type';
    
      return type;
    }
  • 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

    function Calculator() {
    
      // FIXME: shouldn't use a global here
      total = 0;
    
      return this;
    }
  • Use // TODO: to annotate solutions to problems

    function Calculator() {
    
      // TODO: total should be configurable by an options param
      this.total = 0;
    
      return this;
    }

**[⬆ back to top](#table-of-contents)**


## Whitespace

- Never mix spaces and tabs

- Use soft tabs set to 2 spaces

  ```javascript
  // bad
  function() {
  ∙∙∙∙var name;
  }

  // bad
  function() {
  ∙var name;
  }

  // good
  function() {
  ∙∙var name;
  }
  ```

- Remove trailing whitespace

  ```javascript
  // bad
  var foo = 'bar';∙

  // good
  var foo = 'bar';
  ```

- For non-function statements (e.g., if/while/for), place 1 space between the
statement and the leading paren

  ```javascript
  //bad
  if(condition){
    // ...stuff...
  }

  while(condition){
    // ...stuff...
  }

  //good
  if (condition) {
    // ...stuff...
  }

  while (condition) {
    // ...stuff...
  }
  ```

- Place 1 space between paramaters

  ```javascript
  // bad
  foo(bar,baz);

  for (var i=0;i<100;i++) {
    someIterativeFn();
  }

  // good
  foo(bar, baz);

  for (var i = 0; i < 100; i++) {
    // ...stuff...
  }
  ```

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

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

- Insert a newline after functions and label statements.
  ```javascript
  // bad
  if (condition) {

  } else {

  }

  try {

  } catch(e) {

  }

  // good
  if (condition) {

  }
  else {

  }

  try {

  }
  catch(e) {

  }
  ```

- Indent the `case` statements of a `switch`.

  ```javascript
  // bad
  switch (foo) {
  case 'bar':
    // ...stuff...
    break;
  case 'baz':
    // ...stuff...
    break;
  default:
    // ...stuff...
    break;
  }

  // good
  switch (foo) {
    case 'bar':
      // ...stuff...
      break;
    case 'baz':
      // ...stuff...
      break;
    default:
      // ...stuff...
      break;
  }
  ```

**[⬆ back to top](#table-of-contents)**

## Commas

- Leading commas: **Nope.**

  ```javascript
  // bad
  var
    once
    , upon
    , aTime;

  // good
  var
    once,
    upon,
    aTime;

  // bad
  var hero = {
      firstName: 'Clark'
    , lastName: 'Kent'
    , heroName: 'Superman'
    , superPower: 'everything'
  };

  // good
  var hero = {
    firstName: 'Clark',
    lastName: 'Ken',
    heroName: 'Superman',
    superPower: 'everything'
  };
  ```

- 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

- Common types of coercion

  ```javascript
  var
    number = 1,
    string = '1',
    bool = false;

  number; // => 1

  '' + number; // => '1'

  !!number; // => true

  string; // => '1'

  +string; // => 1
  // NOTE: Always prefer #parseInt to + as noted below

  string; // => '1'

  +string++; // => 1

  string; // => 2

  bool; // => false

  +bool; // => 0

  '' + bool; // => 'false'

  ```

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

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

  // good
  var hasAge = Boolean(age);

  // best
  var hasAge = !!age;
  ```

**[⬆ back to top](#table-of-contents)**

## Naming Conventions

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

  ```javascript
  // bad
  function q() {
    // ...stuff...
  }

  // good
  function query() {
    // ..stuff..
  }
  ```

- Use camelCase when naming objects, functions, and instances

  ```javascript
  // bad
  var OBJEcttsssss = {};
  var this_is_my_object = {};
  function c() {}
  var u = new user({
    name: 'Clark Kent'
  });

  // good
  var thisIsMyObject = {};
  function thisIsMyFunction() {}
  var user = new User({
    name: 'Clark Kent'
  });
  ```

- 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'
  });
  ```

- When saving a reference to `this` use `_this`.
- **Note:** This is extremely bug prone and should only be done as a last resort. If you find you are having troubles with `this` being set to the wrong context, consider using the `#call`, `#apply` or `#bind` functions, or
check the documentation to see if a `thisArg` can be passed into a function call.

  ```javascript
  // bad
  function() {
    var self = this;
    return function() {
      console.log(self);
    };
  }

  // bad
  function() {
    var that = this;
    return function() {
      console.log(that);
    };
  }

  // good
  function() {
    var _this = this;
    return function() {
      console.log(_this);
    };
  }
  ```

- Name your functions. This is helpful for stack traces.

  ```javascript
  // bad
  var log = function(msg) {
    console.log(msg);
  };

  // good
  var log = function log(msg) {
    console.log(msg);
  };

  // best (function declaration)
  function log(msg) {
    console.log(msg);
  };
  ```

**[⬆ back to top](#table-of-contents)**

## Accessors

- Accessor functions for properties are not required
- If you do make accessor functions use getVal() and setVal('hello')

  ```javascript
  // bad
  dragon.age();

  // good
  dragon.getAge();

  // bad
  dragon.age(25);

  // good
  dragon.setAge(25);
  ```

- If the property is a boolean, use isVal() or hasVal()

  ```javascript
  // bad
  if (!dragon.age()) {
    return false;
  }

  // good
  if (!dragon.hasAge()) {
    return false;
  }
  ```

- It's okay to create get() and set() functions, but be consistent.

  ```javascript
  function Jedi(options) {
    options || (options = {});
    var lightsaber = options.lightsaber || 'blue';
    this.set('lightsaber', lightsaber);
  }

  Jedi.prototype.set = function(key, val) {
    this[key] = val;
  };

  Jedi.prototype.get = function(key) {
    return this[key];
  };
  ```

- Use the ES5 `get` and `set` keywords to define getters and setters in a more intuitive way as
if they were properties, though they are in fact functions
- **Note:** IE8 and below support is not available for this convention. For more information see [http://ejohn.org/blog/javascript-getters-and-setters/](http://ejohn.org/blog/javascript-getters-and-setters/)

  ```javascript
  function Dragon() {
    var age = 500;

    return {
      get age() {
        return age;
      },
      set age(newValue) {
        age = newValue;
      }
    };
  }

  var dragon = Dragon();
  console.log(dragon.age) // => 500
  dragon.age = 1000;
  console.log(dragon.age) // => 1000
  ```

**[⬆ back to top](#table-of-contents)**


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

  ```javascript
  function Jedi() {
    this.message = 'new jedi';

    console.log(message);

    return this;

    /**
    * when creating a constructor to be instatiated via the `new` keyword,
    * there is an implicit return of `this`, however it is better to be
    * explicit.
    */
  }

  // bad
  Jedi.prototype = {
    fight: function fight() {
      console.log('fighting');
    },

    block: function block() {
      console.log('blocking');
    }
  };

  // good
  Jedi.prototype.fight = function fight() {
    console.log('fighting');
  };

  Jedi.prototype.block = function block() {
    console.log('blocking');
  };
  ```

- Methods can return `this` to help with method chaining.

  ```javascript
  // bad
  Jedi.prototype.jump = function() {
    this.jumping = true;
    return true;
  };

  Jedi.prototype.setHeight = function(height) {
    this.height = height;
  };

  var luke = new Jedi();
  luke.jump(); // => true
  luke.setHeight(20) // => undefined

  // good
  Jedi.prototype.jump = function() {
    this.jumping = true;
    return this;
  };

  Jedi.prototype.setHeight = function(height) {
    this.height = height;
    return this;
  };

  var luke = new Jedi();

  luke.jump()
    .setHeight(20);
  ```

- It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.

  ```javascript
  function Jedi(options) {
    options || (options = {});
    this.name = options.name || 'no name';
  }

  Jedi.prototype.getName = function getName() {
    return this.name;
  };

  Jedi.prototype.toString = function toString() {
    return 'Jedi - ' + this.getName();
  };
  ```

**[⬆ back to top](#table-of-contents)**


## 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:

  ```js
  // bad
  $(this).trigger('listingUpdated', listing.id);

  ...

  $(this).on('listingUpdated', function(e, listingId) {
    // do something with listingId
  });
  ```

  prefer:

  ```js
  // good
  $(this).trigger('listingUpdated', { listingId : listing.id });

  ...

  $(this).on('listingUpdated', function(e, data) {
    // do something with data.listingId
  });
  ```

**[⬆ back to top](#table-of-contents)**


## Modules

- The file should be named with snake case and match the name of the single export written in camel case.

  ```javascript
  // Node module
  // fancy_input/fancy_input.js

  module.exports = FancyInput;

  function FancyInput() {

    function doSomethingFancy(options) {
      options = options || {};
      return true;
    }

    return {
      doSomethingFancy: doSomethingFancy
    };

  }

  // Client-side module
  (function(global) {

    global.FancyModule = FancyModule;

    function FancyModule() {
      var
        data = "secret",
        myArray = [ 1, 2, 3, 4 ];

      return {
        myArray: myArray,
        doSomething: doSomething,
        doSomethingElse: doSomethingElse
      };

      function doSomething() {
        // ...stuff...
      }

      function doSomethingElse() {
        // ...stuff...
      }
    }

  })(this);
  ```

**[⬆ back to top](#table-of-contents)**

## Danger Zone

- `#eval`. Do not use it. It is insecure, can be difficult to debug, and is slow.
- `with`. No.
- `delete`. Avoid if possible due to performance issues. Often the same objective can be achieved by setting the object property to `null` or `undefined`.
- You should not be modifying the `prototype` of built in objects (e.g., `Object.prototype` or `Array.prototype`). Prefer creating a helper utility instead (e.g., the lo-dash library, which provides convenience methods for working with arrays and objects)
- In Node using Waterline, do not use `req.params.all`, which may allow for malicious code execution if javascript is passed in. Instead update each attribute individually.

**[⬆ back to top](#table-of-contents)**

## Testing

- **Yup.**

  + [Jasmine testing framework](http://jasmine.github.io/2.0/introduction.html)
  + [Karma test runner](http://karma-runner.github.io/0.12/index.html)
  + [Protractor e2e framework and runner](https://github.com/angular/protractor)
  + [Istanbul code coverage](http://gotwarlost.github.io/istanbul/)

**[⬆ back to top](#table-of-contents)**

## Resources

- **Basis for the style guide**
  + [Idiomatic.js](https://github.com/rwaldron/idiomatic.js/blob/master/readme.md)
  + [airbnb javascript](https://github.com/airbnb/javascript)
  + [Crockford's Code Conventions](http://javascript.crockford.com/code.html)
  + [Google JS Style Guide](https://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml)

**[⬆ back to top](#table-of-contents)**