Skip to content
This repository has been archived by the owner on Apr 26, 2019. It is now read-only.

howaboutwe/javascript-style-guide

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 

Repository files navigation

HowAboutWe JavaScript Style Guide

A mostly reasonable approach to JavaScript

  1. Objects
  2. Arrays
  3. Strings
  4. Functions
  5. Properties
  6. Variables
  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. jQuery
  18. Modules
  19. ES5 Compatibility
  20. Performance
  21. Resources
  22. In the Wild
  23. Translation
  24. The JavaScript Style Guide Guide
  25. Contributors
  26. License
  • Use the literal syntax for object creation.

    // bad
    var item = new Object();
    
    // good
    var item = {};
  • Don't use reserved words as keys.

    // bad
    var superman = {
      class: 'superhero',
      default: { clark: 'kent' },
      private: true
    };
    
    // good
    var superman = {
      klass: 'superhero',
      defaults: { clark: 'kent' },
      hidden: true
    };

    [⬆]

  • Use the literal syntax for array creation

    // bad
    var items = new Array();
    
    // good
    var items = [];
  • For clarity and performance reasons, cache the length of your arrays in variables outside of the loop

    // bad
    for (var i = 0; i < items.length; i++) {
      // ...stuff...
    }
    
    // bad
    for (var i = 0, len = items.length; i < len; i++) {
      // ...stuff...
    }
    
    // good
    var len = items.length;
    var i;
    
    for (i = 0; i < len; i++) {
      // ...stuff...
    }
  • Always use array#push when appending new values to an array.

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

    var len = items.length;
    var itemsCopy = [];
    var i;
    
    // bad
    for (i = 0; i < len; i++) {
      itemsCopy[i] = items[i];
    }
    
    // good
    itemsCopy = items.slice();
  • To convert an array-like object to an array, use Array#slice.

    function trigger() {
      var args = Array.prototype.slice.call(arguments);
      ...
    }

    [⬆]

  • Use single quotes '' for strings

    // bad
    var name = "Bob Parr";
    
    // good
    var name = 'Bob Parr';
    
    // bad
    var fullName = "Bob " + this.lastName;
    
    // good
    var fullName = 'Bob ' + this.lastName;
    
    // bad
    var fullName = "<a href=\"/name\">Bob " + this.lastName + "</a>";
    
    // good
    var fullName = '<a href="/name">Bob ' + this.lastName + '</a>';
  • Use double quotes "" for interpreted strings inside templates.

    // bad
    var name = users['#{ getUser }'];
    
    // good
    var name = users["#{ getUser }"];
  • 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.';
  • When programatically building up a string, use Array#join instead of string concatenation. Mostly for IE: jsPerf.

    var items;
    var messages;
    var length;
    var i;
    
    messages = [{
        state: 'success',
        message: 'This one worked.'
    },{
        state: 'success',
        message: 'This one worked as well.'
    },{
        state: 'error',
        message: 'This one did not work.'
    }];
    
    length = messages.length;
    
    // bad
    function inbox(messages) {
      items = '<ul>';
    
      for (i = 0; i < length; i++) {
        items += '<li>' + messages[i].message + '</li>';
      }
    
      return items + '</ul>';
    }
    
    // good
    function inbox(messages) {
      items = [];
    
      for (i = 0; i < length; i++) {
        items[i] = messages[i].message;
      }
    
      return '<ul><li>' + items.join('</li><li>') + '</li></ul>';
    }

    [⬆]

  • Function expressions:

    // anonymous function 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.');
    })();
  • 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
    if (currentUser) {
      var test = 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.

    // bad
    function nope(name, options, arguments) {
      // ...stuff...
    }
    
    // good
    function yup(name, options, args) {
      // ...stuff...
    }

    [⬆]

  • 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 users = {
      jane: {},
      john: {}
    };
    
    var userName = getUsername();
    var userObject = users[userName];

    [⬆]

  • 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 additional var declarations for multiple variables and declare each variable on a newline. This is useful when reordering variables and avoiding simple syntax mistakes.

    // bad
    var items = getItems(),
        goSportsTeam = true,
        dragonball = 'z';
    
    // bad
    var items = getItems()
        , goSportsTeam = true
        , dragonball = 'z';
    
    // good
    var items = getItems();
    var goSportsTeam = true;
    var dragonball = 'z';
    var length;
    var i;
  • Assign variables at the top of their scope. 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() {
      if (!arguments.length) {
        return false;
      }
    
      var name = getName();
    
      return true;
    }

    [⬆]

  • 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 !== '') {
      // ...stuff...
    }
    
    // good
    if (name) {
      // ...stuff...
    }
  • For more information see Truth Equality and JavaScript by Angus Croll

    [⬆]

  • Use braces with all blocks.

    // bad
    if (test)
      return false;
    
    // bad
    if (test) return false;
    
    // good
    if (test) {
      return false;
    }
  • Always put blocks and curlys on their own lines.

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

    [⬆]

  • Documentation is highly recommended on Utility Modules. It is optional on all other types of Modules.

  • Don't over document. Opt for descriptive names of variables, functions, and returns over documenting the obvious.

  • Use JSDoc notation for commenting guidelines.

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

    // bad
    // make() returns a new element
    // based on the passed in tag name
    //
    // @param {String} tag
    // @return {Element} element
    function make(tag) {
    
      // ...stuff...
    
      return element;
    }
    
    // good
    /**
     * make() returns a new element
     * based on the passed in tag name
     *
     * @param {String} tag
     * @return {Element} element
     */
    function make(tag) {
    
      // ...stuff...
    
      return element;
    }
  • Use // for single line comments. Always 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;
    }
  • Always specify types and values for all parameters and return values. Ideally, provide a description for the function and parameters as well.

```javascript
// bad
function make(tag) {
  // ...stuff...
}

// good
/**
 * @param {String} tag
 * @return {Element} element
 */
function make(tag) {
  // ...stuff...
}

// best
/**
 * Returns a new element based on the passed in tag name.
 *
 * @param {String} tag
 *  Tag to create. -eg 'a', 'span', 'strong'
 * @return {Element} element
 *  DOM element object.
 */
function make(tag) {

  // ...stuff...

  return element;
}
```

**[[⬆]](#TOC)**
  • Use soft tabs set to 2 spaces

    // bad
    function() {
    ∙∙∙∙var name;
    }
    
    // bad
    function() {
    ∙var name;
    }
    
    // good
    function() {
    ∙∙var name;
    }
  • Place 1 space before the leading brace.

    // 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'
    });
  • Use indentation when making long method chains.

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

    [⬆]

  • Nope.

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

    [⬆]

  • Yup.

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

    [⬆]

  • Perform type coercion at the beginning of the statement.

  • Strings:

    //  => 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';
  • Numbers:

  • 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, leave a comment explaining why and what you're doing.

    var inputValue = '4';
    
    // bad
    var val = new Number(inputValue);
    
    // bad
    var val = +inputValue;
    
    // good
    var val = parseInt(inputValue, 10);

    [⬆]

  • Avoid single letter names. Be descriptive with your naming. These get Uglified anyways.

    // bad
    function q() {
      // ...stuff...
    }
    
    // good
    function query() {
      // ..stuff..
    }
  • Use PascalCase when naming Views, Constructors, Classes, Models, and Collections.

    // 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 lower camelCase for everything else (e.g.- objects, functions, and instances).

    // 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'
    });
  • When saving a reference to this use self.

    // bad
    function() {
      var that = this;
      return function() {
        console.log(that);
      };
    }
    
    // good
    function() {
      var self = this;
      return function() {
        console.log(self);
      };
    }
  • Name your functions. This is helpful for stack traces.

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

    [⬆]

  • Accessor functions for properties are not required

  • If you do make accessor functions, always prepend with get and set. Eg- getVal() and setVal('hello').

    // bad
    dragon.age();
    
    // good
    dragon.getAge();
    
    // bad
    dragon.age(25);
    
    // good
    dragon.setAge(25);
  • If the property is a boolean, use isVal() or hasVal()

    // bad
    if (!dragon.age()) {
      return false;
    }
    
    // good
    if (!dragon.hasAge()) {
      return false;
    }
  • It's okay to create get() and set() functions, but be consistent.

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

    [⬆]

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

    function Jedi() {
      console.log('new jedi');
    }
    
    // bad
    Jedi.prototype = {
      fight: function fight() {
        console.log('fighting');
      },
    
      block: function block() {
        console.log('blocking');
      }
    };
    
    // good
    Jedi.prototype.fight = function fight() {
      console.log('fighting');
    };
    
    Jedi.prototype.block = function block() {
      console.log('blocking');
    };
  • Methods can return this to help with method chaining.

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

    [⬆]

  • Prefix jQuery object variables with a $.

    // bad
    var sidebar = $('.sidebar');
    
    // good
    var $sidebar = $('.sidebar');
    
    // bad
    var $primary_nav = $('#primary-nav');
    
    // good
    var $primaryNav = $('#primary-nav');
  • If a jQuery lookup is performed more than once, cache the jQuery object.

    // bad
    function setSidebar() {
      $('.sidebar').hide();
    
      // ...stuff...
    
      $('.sidebar').css({
        'background-color': 'pink'
      });
    }
    
    // bad
    function getSideBarHeight() {
      var $sidebar = $('.sidebar');
    
      $sidebar.height();
    }
    
    // good
    function getSideBarHeight() {
      $('.sidebar').height();
    }
    
    // good
    function setSidebar() {
      var $sidebar = $('.sidebar');
      $sidebar.hide();
    
      // ...stuff...
    
      $sidebar.css({
        'background-color': 'pink'
      });
    }
  • For DOM queries use Cascading $('.sidebar ul') or parent > child $('.sidebar > ul'). jsPerf

  • Use find with scoped jQuery object queries.

    // bad
    $('.sidebar', 'ul').hide();
    
    // bad
    $('.sidebar').find('ul').hide();
    
    // good
    $('.sidebar ul').hide();
    
    // good
    $('.sidebar > ul').hide();
    
    // good (slower)
    $sidebar.find('ul');
    
    // good (faster)
    $($sidebar[0]).find('ul');
  • Don't combine elements with a class or ID as part of the selector. If this results in selecting elements you don't want, you probably need to refactor your DOM.

    // bad
    $('form#new_user').submit();
    
    // bad
    $('li.user').hide();
    
    // good
    $('#new_user').submit();
    
    // good
    $('.user').hide();

    [⬆]

  • We use the JavaScript Module Pattern, as defined by Ben Cherry. Read up on it here.

  • Files should be named with camelCase, live in their appropriate folder (views/ utils/ etc), and match the name of the single export.

  • Always declare 'use strict;' at the top of the module.

  • Always return the original module object.

  • If you need to reference any other global objects, pass it to the module's arguments to help provide faster lookups and prevent linting errors.

    /*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, jquery:true, indent:2, maxerr:100 */
    
    /*
      @namespace viewName
      @memberOf haw.views
    */
    var haw = (function (module, $) {
      'use strict';
    
      // Module Namespace Extension
      var views = module.views = module.views || {};
      var viewName = views.viewName = views.viewName || {};
    
    
      // Private Variables
      var foo = "bar";
    
      // Private Method
      function privateMethod () {}
    
      // Public API
      viewName.publicMethod = function () {};
    
      // Return the extended module
      return module;
    
    }(haw || {}, jQuery));

    [⬆]

[⬆]

[⬆]

Read This

Other Styleguides

Other Styles

Books

Blogs

Additional Articles

[⬆]

This is a list of organizations that are using this style guide. Send us a pull request or open an issue and we'll add you to the list.

This style guide is also available in other languages:

(The MIT License)

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

[⬆]

Releases

No releases published

Packages

No packages published