Skip to content

asawilliams/javascript

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 

Repository files navigation

JavaScript Style Guide

Intro

The intention of this style guide is to get contributers on the same page to help a project be more successful.

"All code in any code-base should look like a single person typed it, no matter how many people contributed." https://github.com/rwldrn/idiomatic.js

 

"Arguments over style are pointless. There should be a style guide, and you should follow it" Rebecca Murphey

 

"Part of being a good steward to a successful project is realizing that writing code for yourself is a Bad Idea™. If thousands of people are using your code, then write your code for maximum clarity, not your personal preference of how to get clever within the spec." Idan Gazit

  1. Variables
  2. Objects
  3. Arrays
  4. Strings
  5. Functions
  6. Properties
  7. Conditional Expressions & Equality
  8. Blocks
  9. Comments
  10. Whitespace
  11. Leading Commas
  12. Semicolons
  13. Type Casting & Coercion
  14. Naming Conventions
  15. Accessors
  16. Constructors
  17. Modules
  18. License
  • 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;
    
    // good
    var superPower;
  • Use one var declaration for multiple variables 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;
  • Assign variables at the top of their context (not necessarily the top of the scope). This helps avoid issues with variable declaration and assignment hoisting related issues.

    // bad, str should be defined before calling test()
    function() {
        test();
        var str = 'string';
    }
    
    // good
    function() {
        var str = 'string';
        test();
    }

-It is better though to keep variables in context than to force the declaration at the top of the scope. A good example is when you want to break out the computation of a value into multiple pieces to read it better.

```javascript
// bad, i and len are declared out of the context they are used
function() {
    var i = 0,
        len = array.length;

    [lots of code ...]

    for( ; i < len; i++) {

    }
}

// good
function() {
    [lots of code]

    for(var i = 0, len = array.length; i < len; i++) {

    }
}
```

**[[⬆]](#TOC)**
  • Use the literal syntax for object creation.

    // bad
    var item = new Object();
    
    // good
    var item = {};
  • Define all the keys on object creation

    // bad
    var item = {};
    item.prop = 'value';
    item.name = 'name';
    
    // good
    var item = {
        prop: 'value',
        name: 'name',
    };
  • 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.

    var luke = {
        jedi: true,
        age: 28
    };
    
    function getProp(prop) {
        return luke[prop];
    }
    
    var isJedi = getProp('jedi');
  • Use the literal syntax for array creation

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

    var someStack = [];
    
    // bad
    someStack[someStack.length] = 'abracadabra';
    
    // good
    someStack.push('abracadabra');
  • Use single quotes '' for strings

    // bad
    var name = "Bob Parr";
    
    // good
    var name = 'Bob Parr';
  • 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.';
  • Function expressions:

    // anonymous function expression
    // by giving the function a name it makes it easier to debug since anonymous.name is now equal to 'myFunc'
    // instead of ''.
    var anonymous = function myFunc() {
        return true;
    };
    
    // named function expression
    function named() {
        return true;
    };
    
    // 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.

    // bad
    if (currentUser) {
        function test() {
            console.log('Nope.');
        }
    }
    
    // good
    var test;
    if (currentUser) {
        test = function test() {
            console.log('Yup.');
        };
    }

    [⬆]

  • There should be a space after the

    if[space]([expression])[space]{  
    [tab]
    }
  • 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 evalute 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.

    // bad
    if (name !== '') {
        // [code]
    }
    
    // good
    if (name) {
        // [code]
    }
    
    // bad
    if (collection.length !== 0) {
        // [code]
    }
    
    // good
    if (collection.length) {
        // [code]
    }
  • For more information see Truth Equality and JavaScript by Angus Croll

    [⬆]

  • Use braces with all multi-line blocks.

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

    [⬆]

  • Use /** ... */ for multiline comments. Include a description, specify types and values for all parameters and return values.

    /**
     * Method Description
     * 
     * @param  {String}   name                      name of the user to find
     * @param  {Object}   parent                    parent object
     * @param  {String}   parent.username           parent's username
     * @param  {Int}      [parent.age]              optional parameter
     * @param  {Boolean}  [parent.isGaurdian=true]  optional parameter, defaults to true
     * @param  {Person[]} [siblings]                optional parameter, array of Person objects
     * @return {User}     first result that matches the name and parent
     */
    function getUser(name, parent, siblings) {
        return user;
    }
  • Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an emptyline 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;
    }

  **[[⬆]](#TOC)**


## <a name='whitespace'>Whitespace</a>

- Use tabs not spaces for indenting  
- Why tabs are better than spaces: http://lea.verou.me/2012/01/why-tabs-are-clearly-superior/

  ```javascript
  function[space]name(arg1,[space]arg2)[space]{
  [tab]var name;
  }

  ```
- Place 1 space before the leading brace.

  ```javascript
  // bad
  function test(){
      // [code]
  }

  // good
  function test() {
      // [code]
  }

  // bad
  dog.set('attr',{
      age: '1 year',
      breed: 'Bernese Mountain Dog'
  });

  // good
  dog.set('attr', {
      age: '1 year',
      breed: 'Bernese Mountain Dog'
  });
  ```

- Use indentation when making long method chains.  Try not to over chain.  3 or 4 is about the max recommended.

  ```javascript
  // bad
  $('#items').find('.selected').highlight().end().find('.open').updateCount();

  // good
  $('#items')
      .removeClass('selected')
      .css('top', 20);
  ```

  **[[⬆]](#TOC)**

## <a name='leading-commas'>Leading Commas</a>

- **Nope.**

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

  // good
  var once,
      upon,
      aTime;

  // bad
  var hero = {
      firstName: 'Bob'
    , lastName: 'Parr'
    , heroName: 'Mr. Incredible'
    , superPower: 'strength'
  };

  // good
  var hero = {
      firstName: 'Bob',
      lastName: 'Parr',
      heroName: 'Mr. Incredible',
      superPower: 'strength'
  };
  ```

  **[[⬆]](#TOC)**


## <a name='semicolons'>Semicolons</a>

- **Yup.**

  ```javascript
  // bad
  (function() {
      var name = 'Skywalker'
      return name
  })()

  // good
  (function() {
      var name = 'Skywalker';
      return name;
  })();

  // good
  ;(function() {
      var name = 'Skywalker';
      return name;
  })();
  ```

  **[[⬆]](#TOC)**


## <a name='type-coercion'>Type Casting & Coercion</a>

- Use `parseInt` for Numbers and always with a radix for type casting.
- 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
  var inputValue = '4';

  // bad
  var val = new Number(inputValue);

  // bad
  var val = +inputValue;

  // bad
  var val = inputValue >> 0;

  // bad
  var val = parseInt(inputValue);

  // bad
  var val = Number(inputValue);

  // good
  var val = parseInt(inputValue, 10);

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

- Booleans:

  ```javascript
  var age = 0;

  // bad
  var hasAge = new Boolean(age);

  // bad
  var hasAge = Boolean(age);

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

  **[[⬆]](#TOC)**


## <a name='naming-conventions'>Naming Conventions</a>

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

  ```javascript
  // bad
  function q() {
      // [code]
  }

  // good
  function query() {
      // [code]
  }
  ```

- Event Handlers should start with 'on' then the object the event is coming from, and then the event type

  ```javascript
  // bad
  function openDialog() {
      // [code]
  }

  // good
  function onButtonClick() {
      // [code]
  }
  ```

- Use camelCase when naming objects, functions, and instances

  ```javascript
  // bad
  var OBJEcttsssss = {};
  var this_is_my_object = {};
  var this-is-my-object = {};

  function c() {};

  var u = new user({
      name: 'Bob Parr'
  });

  // good
  var thisIsMyObject = {};

  function thisIsMyFunction() {};

  var user = new User({
      name: 'Bob Parr'
  });
  ```

- Use 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 in a class 

  ```javascript
  // bad
  function User() {
      this.__firstName__ = 'Panda';
      this.firstName_ = 'Panda';
  }

  // good
  function User() {
      this._firstName = 'Panda';
  }
  ```

- When saving a reference to `this` use `self`.

  ```javascript
  // bad
  function() {
      var that = this;

      return function() {
          console.log(that);
      };
  }

  // good
  function() {
      var self = this;

      return function() {
          console.log(self);
      };
  }
  ```

- Booleans should start with either 'is' or 'has'.

  ```javascript
  // bad
  var male = false

  // good
  var isMale = false;
  ```

  **[[⬆]](#TOC)**


## <a name='accessors'>Accessors</a>

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

## <a name='constructors'>Constructors</a>

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

  ```javascript
  function Jedi() {
      console.log('new jedi');
  }

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

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

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

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

## <a name='modules'>Modules</a>

- The module should start with a `!`. This ensures that if a malformed module forgets to include a final semicolon there aren't errors in production when the scripts get concatenated.
- The file should be named with camelCase, live in a folder with the same name, and match the name of the single export.
- Add a method called noConflict() that sets the exported module to the previous version and returns this one.
- Always declare `'use strict';` at the top of the module.

  ```javascript
  // fancyInput/fancyInput.js

  !function(global) {
      'use strict';

      var previousFancyInput = global.FancyInput;

      function FancyInput(options) {
          this.options = options || {};
      }

      FancyInput.noConflict = function noConflict() {
          global.FancyInput = previousFancyInput;
          return FancyInput;
      };

      global.FancyInput = FancyInput;
  }(this);
  ```

  **[[⬆]](#TOC)**

## <a name='license'>License</a>

(The MIT License)

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.

**[[⬆]](#TOC)**


About

JavaScript Style Guide

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published