Thursday, April 2, 2015

JavaScript Style Guide

Everything about javascript from basic to advanced.


Airbnb JavaScript Style Guide() {

A mostly reasonable approach to JavaScript

Table of Contents

  1. Types
  2. Objects
  3. Arrays
  4. Strings
  5. Functions
  6. Properties
  7. Variables
  8. Hoisting
  9. Comparison Operators & 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. ECMAScript 5 Compatibility
  23. Testing
  24. Performance
  25. Resources

Types

  • Primitives: When you access a primitive type you work directly on its value.
    • string
    • number
    • boolean
    • null
    • undefined
    var foo = 1;
    var 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];
    var bar = foo;
    
    bar[0] = 9;
    
    console.log(foo[0], bar[0]); // => 9, 9

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
    };
  • Use readable synonyms in place of reserved words.
    // bad
    var superman = {
      class: 'alien'
    };
    
    // bad
    var superman = {
      klass: 'alien'
    };
    
    // good
    var superman = {
      type: 'alien'
    };

Arrays

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

Strings

  • 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;
  • 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 programmatically 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] = '<li>' + messages[i].message + '</li>';
      }
    
      return '<ul>' + items.join('') + '</ul>';
    }

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

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

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 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.
    // bad
    var items = getItems(),
        goSportsTeam = true,
        dragonball = 'z';
    
    // bad
    // (compare to above, and try to spot the mistake)
    var items = getItems(),
        goSportsTeam = true;
        dragonball = 'z';
    
    // good
    var items = getItems();
    var goSportsTeam = true;
    var 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;
    var items = getItems();
    var dragonball;
    var goSportsTeam = true;
    var len;
    
    // good
    var items = getItems();
    var goSportsTeam = true;
    var dragonball;
    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;
    }

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.

Comparison Operators & Equality

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

Blocks

  • Use braces with all multi-line blocks.
    // bad
    if (test)
      return false;
    
    // good
    if (test) return false;
    
    // good
    if (test) {
      return false;
    }
    
    // bad
    function() { return false; }
    
    // good
    function() {
      return false;
    }
  • If you're using multi-line blocks with if and else, put else on the same line as your if block's closing brace.
    // bad
    if (test) {
      thing1();
      thing2();
    }
    else {
      thing3();
    }
    
    // good
    if (test) {
      thing1();
      thing2();
    } else {
      thing3();
    }

Comments

  • Use /** ... */ for multiline comments. 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} 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. 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;
    }

Whitespace

  • 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'
    });
  • Set off operators with spaces.
    // bad
    var x=y+5;
    
    // good
    var x = y + 5;
  • End files with a single newline character.
    // bad
    (function(global) {
      // ...stuff...
    })(this);
    // bad
    (function(global) {
      // ...stuff...
    })(this);↵
    ↵
    // 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.
    // 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
    // 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;

Commas

  • Leading commas: Nope.
    // 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):
    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.
      // bad
      var hero = {
        firstName: 'Kevin',
        lastName: 'Flynn',
      };
    
      var heroes = [
        'Batman',
        'Superman',
      ];
    
      // good
      var hero = {
        firstName: 'Kevin',
        lastName: 'Flynn'
      };
    
      var heroes = [
        'Batman',
        'Superman'
      ];

Semicolons

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

Type Casting & Coercion

  • 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';
  • Use parseInt for Numbers and always with a radix for type casting.
    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 forperformance reasons, leave a comment explaining why and what you're doing.
    // 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, but Bitshift operations always return a 32-bit integer (source). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion. Largest signed 32-bit Int is 2,147,483,647:
    2147483647 >> 0 //=> 2147483647
    2147483648 >> 0 //=> -2147483648
    2147483649 >> 0 //=> -2147483647
  • Booleans:
    var age = 0;
    
    // bad
    var hasAge = new Boolean(age);
    
    // good
    var hasAge = Boolean(age);
    
    // good
    var hasAge = !!age;

Naming Conventions

  • Avoid single letter names. Be descriptive with your naming.
    // bad
    function q() {
      // ...stuff...
    }
    
    // good
    function query() {
      // ..stuff..
    }
  • Use camelCase when naming objects, functions, and instances.
    // 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.
    // 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.
    // bad
    this.__firstName__ = 'Panda';
    this.firstName_ = 'Panda';
    
    // good
    this._firstName = 'Panda';
  • When saving a reference to this use _this.
    // 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.
    // bad
    var log = function(msg) {
      console.log(msg);
    };
    
    // good
    var log = function log(msg) {
      console.log(msg);
    };
  • Note: IE8 and below exhibit some quirks with named function expressions. See http://kangax.github.io/nfe/ for more info.
  • If your file exports a single class, your filename should be exactly the name of the class.
    // file contents
    class CheckBox {
      // ...
    }
    module.exports = CheckBox;
    
    // in some other file
    // bad
    var CheckBox = require('./checkBox');
    
    // bad
    var CheckBox = require('./check_box');
    
    // good
    var CheckBox = require('./CheckBox');

Accessors

  • Accessor functions for properties are not required.
  • If you do make accessor functions use 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];
    };

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!
    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);
  • It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects.
    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();
    };

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

Modules

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

jQuery

  • Prefix jQuery object variables with a $.
    // bad
    var sidebar = $('.sidebar');
    
    // good
    var $sidebar = $('.sidebar');
  • Cache jQuery lookups.
    // bad
    function setSidebar() {
      $('.sidebar').hide();
    
      // ...stuff...
    
      $('.sidebar').css({
        'background-color': 'pink'
      });
    }
    
    // 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
    $('ul', '.sidebar').hide();
    
    // bad
    $('.sidebar').find('ul').hide();
    
    // good
    $('.sidebar ul').hide();
    
    // good
    $('.sidebar > ul').hide();
    
    // good
    $sidebar.find('ul').hide();

ECMAScript 5 Compatibility

Testing

  • Yup.
    function() {
      return true;
    }

Performance

Resources

Read This
Tools
Other Styleguides
Other Styles
Further Reading
Books
Blogs
Podcasts

In the Wild

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.

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.

};


Everything developer should know








Developers and Open Source authors now have a massive amount of services offering free tiers, but it can be hard to find them all in order to make informed decisions.

This is list of software (SaaS, PaaS, IaaS, etc.) and other offerings that have free tiers for developers.

The scope of this particular list is limited to things infrastructure developers (System Administrator, DevOps Practitioners, etc.) are likely to find useful. We love all the free services out there, but it would be good to keep it on topic.  It's a bit of a grey line at times so this is a bit opinionated; do not be offended if I do not accept your contribution.

You can help by sending Pull Requests to add more services. Once I have a good set of links in this README file, I'll look into a better layout for the information and links (help with that is appreciated too).

If you're not inclined to make PRs you can tweet me at ```@ripienaar```


## Source Code Repos

  * https://bitbucket.org/ - Unlimited public and private git repos for small teams
  * https://github.com – Free for an unlimited number of public repositories
  * https://about.gitlab.com/ - Unlimited public and private git repos with unlimited collaborators

## Tools for teams & Collaboration

  * http://appear.in/ - One click video conversations, for free
  * http://www.hall.com/ - Free for unlimited users with some feature limitations
  * https://www.flowdock.com/ - Chat and inbox, free for teams of 5 or less
  * https://slack.com - Free for unlimited users with some feature limitations
  * https://hipchat.com - Free for unlimited users with some feature limitations
  * https://gitter.im - "Chat, for GitHub". Unlimited public & private rooms, free for teams of up to 25
  * http://www.google.com/hangouts/ - One place for all your Conversations, for free (Need Google Account)
  * https://kato.im - Team Chat & Collaboration, free for unlimited users with some feature limitations
  * http://seafile.com/ - Private or cloud storage, file sharing, sync, discussions. Private version is full. Cloud version has just 1 GB.

## Code Quality

  * https://landscape.io/ - Code Quality for Python projects, free for Open Source
  * https://codeclimate.com/ - Automated code review, free for Open Source
  * https://houndci.com/ - Comments on github commits about code quality - free for Open Source
  * https://coveralls.io/ - Display test coverage reports - free for open source
  * https://scrutinizer-ci.com/ - Continuous inspection platform - free for Open Source
  * https://codecov.io/ - Code coverage tool (SaaS), free for 1 private project and no restrictions for publics repos
  * https://insight.sensiolabs.com/ _ Code Quality for PHP/Symfony projects, free for Open Source

## Code Search and Browsing
  * https://sourcegraph.com/ - Java, Go, Python, Node.js, etc., code search/cross-references - free for open source
  * https://searchcode.com/ - comprehensive text-based code search - free for open source

## CI / CD

  * https://codeship.com/ - 100 private builds / month, 5 private projects.  Unlimited for Open Source
  * https://circleci.com – Free for one concurrent build
  * https://travis-ci.org – Free for public Github repositories.
  * http://wercker.com/ - Free for public and private repositories
  * https://drone.io/ - CI platform that includes browser testing, free for Open Source
  * https://semaphoreci.com/ - 100 private builds / month. Unlimited for Open Source.
  * http://www.shippable.com/ - Free for 1 build container, private and public repos, unlimited builds.
  * https://snap-ci.com - Free for public repositories, 1 build at the time
  * http://www.appveyor.com/ - CD service for Windows. Free for open-source projects.
  * [Comparison of Continuous Integration services](https://github.com/ligurio/Continuous-Integration-services)
  * https://saucelabs.com/ - CI with scalable testing for mobile and web apps, free for Open Source
  * http://ftploy.com/ - 1 project w/ unlimited deployments
  * https://deployhq.com/ - 1 project w/ 10 daily deployments

## Security and PKI

  * http://vaddy.net - Continuous web security testing with continuous integration (CI) tools. 3 domains, 10 scan history for free
  * https://www.globalsign.com/en/ssl/ssl-open-source/ - Free SSL certs for Open Source projects
  * https://www.startssl.com/ - Free SSL certs
  * https://stormpath.com/ - Free user management, authentication, social login, and SSO.
  * https://auth0.com/ - Hosted free for development SSO
  * https://getclef.com/ - New take on auth unlimited free tier for anyone not using premium features
  * https://ringcaptcha.com/ - Tools to use phone number as id, available for free
  * https://www.ssllabs.com/ssltest/ - Very deep analysis of the configuration of any SSL web server
  * https://qualys.com/forms/freescan/owasp/ - Find web app vulnerabilities, audit for OWASP Risks
  * [alienvault.com ThreatFinder](https://www.alienvault.com/open-threat-exchange/threatfinder) - Uncovers compromised systems in your metwork

## Management Systems

  * https://opbeat.com/ - Release, deploy, monitor.  Free for 3 users

## Log Management

  * https://papertrailapp.com/ - 48 hours search, 7 day archive, 100MB/month
  * https://logentries.com/ - Free up to 5GB/month with 7 day retention
  * https://www.loggly.com/ - Free for a single user, see the ```lite``` option
  * http://sematext.com/logsene - Free for 1M logs, unlimited retention

## Analytics

  * http://www.splunk.com/en_us/products/splunk-cloud.html - Upload 5GB of data per day up to 28GB of total data stored
  * https://parse.com - Unlimited free analytics

## Monitoring

  * https://www.thousandeyes.com  - Network & user experience monitoring. 3 locations, plus 20 data feeds of major web services free.
  * https://www.datadoghq.com/ - Free for up to 5 nodes
  * http://www.stackdriver.com/ - Free for up to 10 nodes/services
  * https://keymetrics.io/ - Free for 2 servers with 7 days data retention
  * http://newrelic.com/ - Free with 24 hour data retention
  * https://nodequery.com/ - Free basic server monitor up to 10 servers
  * https://www.pingdom.com/free/ - 1 site free
  * https://www.opsgenie.com/ - Alert management with mobile push. 600 free alerts for 2 users a month
  * https://www.runscope.com/ - Monitor and log API usage.  Single user 10,000 request/month free
  * http://www.circonus.com/ - Free for 20 metrics
  * https://uptimerobot.com/ - Website monitoring, 50 monitors free
  * https://www.statuscake.com/ - Website monitoring, unlimited tests free with limitations
  * http://www.boundary.com/ - Free 1 second resolution for up to 10 servers
  * https://ghostinspector.com/ - Free website and web application monitoring. Single user, 100 test runs per month
  * http://java-monitor.com/ - Free monitoring of JVM's and uptime
  * http://sematext.com/spm - Free for 24h metrics, unlimited number of servers, 10 custom metrics, 500K custom metrics data points, unlimited dashboards, users, etc.
  * https://sealion.com/ - Free up to 2 servers, 3 days data retention, graphs and raw command output history (`top`, `ps`, `ifconfig`, `netstat`, `iostat`, `free`, custom, etc.)
  * https://www.stathat.com - Get started with ten stats for free, no expiration.

## Crash / Exception handling

  * https://rollbar.com/ - Exception and error monitoring, free plan - 5000 errors/month, unlimited users, 30 days retention.
  * https://bugsnag.com/ - Free for up to 2000 errors a month after the initial trial
  * https://airbrake.io/ - Free for 1 project, 1 user, 2 errors per minute, 2 day retention
  * http://getsentry.com/ - Sentry tracks app exceptions in realtime, has a small free plan

## Search

  * https://swiftype.com – hosted search solution (API and crawler). Free for a single search engine with up to 1000 documents. Free upgrade to Premuim level for open-source projects.
  * https://bonsai.io - Free 1GB memory and 1GB storage.
  * http://www.searchly.com - Free 2 Indices and 5MB storage.

## Email

  * http://www.mailgun.com/ - First 10,000 emails per month are free
  * http://mailchimp.com/ - Send 12,000 emails to 2,000 subscribers for free
  * http://sendgrid.com/ - 400 emails per day for free
  * http://mandrill.com/ - First 12,000 emails are free
  * https://www.phplist.com/ - Hosted version allow 300 mails per month for free
  * https://www.mailjet.com/ - 6000 mails per month for free
  * https://www.sendinblue.com/ - 9000 mails per month for free

## CDN and Protection

  * http://www.cloudflare.com/ - Basic service is free, good for a blog
  * http://www.bootstrapcdn.com/ - CDN for bootstrap, bootswatch and font awesome
  * https://surge.sh - Zero-bullshit, single–command, bring your own source control web publishing CDN.

## PaaS

  * http://aws.amazon.com/free/ - AWS Free Tier - Free for 12 months
  * https://cloud.google.com/appengine/ - Google App Engine gives 28 instance hours free, 1Gb NoSQL Database and more.
  * https://www.engineyard.com - Engine Yard provides 500 free hours
  * http://azure.microsoft.com/ - MS Azure gives $200 worth of free usage for a trial
  * http://hpcloud.com/ - $300 credit over 90 days.
  * https://appharbor.com/ - A .Net PaaS that provides 1 free worker
  * https://www.heroku.com/ - Host your apps in the cloud, free for single process apps
  * https://www.firebase.com/ - Build realtime apps, free plan has 50 Max Connections, 5 GB Data Transfer, 100 MB Data Storage.
1 GB Hosting Storage and 100 GB Hosting Transfer.
  * https://bluemix.net/ - IBM PaaS with a monthly free allowance
  * https://www.openshift.com/ - RedHat OpenShift offers 3 free hosted apps
  * https://bitnami.com/ - One free small app
  * https://scalingo.com - Free Tier, up to 3 apps, 1 container each, combined with data store addons free tier
  * https://algorithmia.com - Host algorithms for free - includes 10,000 credits (seconds of on-demand execution time) free
  * https://bigml.com/ - Hosted machine learning algorithms. Unlimited free tasks for development, limit of 16MB data per task
  * https://www.activestate.com/stackato/ - Enterprise-hardened Cloud Foundry PaaS from ActiveState, for private, public and hybrid cloud, free up to 20GB

## BaaS
  * https://www.parse.com - Mobile backends, free plan has 30 requests per second, with 20 GB of file and database storage, as well as push notifications for up to 1,000,000 unique recipients.


## Web Hosting

  * https://www.simplybuilt.com - SimplyBuilt offers free website building and hosting for open source projects (http://www.simplybuilt.com/explore/free-websites-for-open-source-projects). Simple alternative to GitHub Pages.
  * https://www.devport.co - Turn GitHub projects, Apps, and websites into a personal developer portfolio.

## IaaS

  * https://exoscale.ch/ - Free resources for Open Source projects
  * https://cloudant.com/ - Hosted database from IBM, free if usage is below $50/month
  * https://developer.rackspace.com/ - Rackspace Cloud gives $50/month for 12 months
  * https://cloud.google.com/compute/ - Google Compute Engine gives $300 over 60 days
  * https://cloud.google.com/container-engine/ - Google Container Engine for run Docker containers(Alpha). Pricing: same of Google Compute Engine.
  * https://nsone.net/ - Data Driven DNS, automatic traffic management, 1M free Queries

## DBaaS
   * https://mongolab.com/ - MongoDB as a service (500mb free)
   * https://realm.io - Free to use even for commercial projects, under Apache 2.0 License
   * https://orchestrate.io/ - 1 application free
   * https://redislabs.com/redis-cloud - Redis as a Service (25 mb free)
   * https://www.backand.com/ - Back-end as a service (for AngularJS)
   * http://www.zenginehq.com - Build business workflow apps in minutes - free for single users
   * https://parsehub.com/ — Extract data from dynamic sites, turn dynamic websites into APIs, 5 projects free.
   * https://import.io/ - Easily turn websites into APIs, completely free for life.

## STUN, WebRTC, Web Socket Servers and other Routers
   * https://pusher.com. Hosted Web Sockets broker. Free for up to 20 simultaneous connections and 100k messages a day.
   * stun:stun.l.google.com:19302 - Google STUN
   * stun:global.stun.twilio.com:3478?transport=udp - Twilio STUN
   * https://www.segment.com. Hub to translate and route events to other third party services. 100k events a month free.

## Issue tracking / Project management

   * https://www.atlassian.com/opensource/overview - Free Jira etc for Open Source projects
   * https://kanbanflow.com/ - Board based project management. Free (premium version with more options).
   * https://kanbanpad.com/ - Board based project management. Free (premium version with more options).
   * https://kanbanery.com/ - Board based project management. Free for 2 users (premium tiers with more options).
   * https://trello.com/ - Board based project management. Free
   * https://waffle.io/ - Board based project management solution from your existing GitHub Issues. Free for open-source.
   * https://huboard.com/ - Instant project management for your GitHub issues. Free for open-source.
   * https://taiga.io/ - Project management platform for startups and agile developers. Free for open-source.
   * https://www.jetbrains.com/youtrack/buy/open_source_incloud.jsp - Free hosted YouTrack (InCloud) for FOSS projects (private projects free for 10 users: https://www.jetbrains.com/youtrack/buy/)
   * https://github.com - In addition to its git storage facility, github offers basic issue tracking
   * https://asana.com - Free for private project with collaborators.
   * http://www.acunote.com/ - Free project management and SCRUM software for up to 5 team members.
   * http://gliffy.com/ - Online diagrams: flowchart, UML, wireframe... Also Plugins for Jira & Confluence. 5 diagrams and 2 MB free.
   * https://cacoo.com/ - Online diagrams in real time: flowchart, UML, network. Free max. 15 users/diagram, 25 sheets.


## Storage and Media Processing

   * https://www.aerofs.com/ - P2P file syncing, free for up to 30 users
   * http://cloudinary.com - Image upload, powerful manipulations, storage, and delivery for sites and apps, with libraries for Ruby, Python, Java, PHP, Objective-C and more. Perpetual free tier includes 7500 images/month, 2gb storage, 5gb bandwidth.
   * https://plot.ly - graph and share your data. Free tier includes unlimited public files and 10 private files.

## Package Build Systems

   * https://build.opensuse.org/ - package build service for multiple distros (SUSE, EL, Fedora, Debian etc.)
   * https://copr.fedoraproject.org/ - mock-based RPM build service for Fedora and EL
   * https://help.launchpad.net/Packaging - Ubuntu and Debian build service

## IDE and Code Editing

   * https://c9.io - IDE in a browser. Incorporates an Ubuntu virtual machine and in-browser terminal access. Integrates with github and bitbucket, but also adds SFTP and generic Git access.
   * https://koding.com - IDE in a browser. Features: Full sudo access - VMs hosted on Amazon EC2 - SSH Access - Real EC2 VM, no LXCs/hypervising - Custom sub-domains - Publicly accessible IP - Ubuntu 14.04 - IDE/Terminal/Collaboration
   * https://www.nitrous.io - Private Linux instance(s) with interactive collaboration {[More Details](http://goo.gl/J1Zbsg)}
   * http://visualstudio.com/free - Fully-featured IDE with thousands of extensions, cross-platform app development (Microsoft extensions available for download for iOS and Android), desktop, web and cloud development, multi-language support (C#, C++, JavaScript, Python, PHP and more).
   * https://wakatime.com - quantified self metrics about your coding activity, using text editor plugins - Limited plan for free.
   * https://codenvy.com/ - IDE in a browser, collaborative, git integration, build and run your app in customizable Docker-based runners (free 512Mb RAM to distribute between you runners), pre-integrated deploy to Google Apps.
   * https://apiary.io/ - Collaborative design API with instant API mock and generated documentation (Free for unlimited API blueprints and unlimited user with one admin account and hosted documentation)
   * https://www.jetbrains.com/ruby/ - RubyMine IDE primarily used for Ruby/RoR Projects. Free license for students, teachers, open source projects, and user groups.

## Analytics, Events and  Statistics

 * https://www.librato.com/ - Event/Data collection service with analysis and graphs. Limited plan for free.
 * https://google.com/analytics/ - Google Analytics
 * http://sematext.com/search-analytics - Free for up to 50K actions/month, 1 day data retention, unlimited dashboards, users, etc.
 * https://usabilityhub.com - Test designs and mockups on real people, track visitors. Free for one user, unlimited tests.

## Other Packs

 * https://education.github.com/pack - As long as you're a student at a recognized university

## Docker Related
### Alternate container hosting

  * https://quay.io/ - Unlimited free public containers

## Vagrant Related
### Vagrant box indexes

  * https://atlas.hashicorp.com/boxes/search - HashiCorp's index of boxes
  * http://vagrantbox.es - An alternative public box index

## Data mining
  * http://www.monkeylearn.com/ - Text mining in the cloud, 1,000 queries for free per month.

Source:

https://github.com/ripienaar/free-for-dev

Wednesday, April 1, 2015

A HTML-driven JavaScript-library for narrative 3D-scrolling


Page: http://www.slashie.org/space.js/
Demo: http://www.slashie.org/space.js/demo1.html
A HTML-driven JavaScript-library for narrative 3D-scrolling. NOTE THAT SHOULD BE CONSIDERED TO BE BETA SOFTWARE Production use is not recommended at this point.
Usage
 Import the library

<head>
    <script type="text/javascript" src="[jquery]"></script>
    ...
</head>
<body>
    [Your contents]
    <script type="text/javascript" src="space.min.js"></script>
</body>

The library is HTML-driven, which means that you don't need to write a single line of JavaScript to use it on your site and still have a lot of flexibility!
The core of the library is to divide our HTML into frames, or space-frames as we call them her (to not conflict the common class name "frame").

Creating a frame


<div class="space-frame">[contents]</div>
I would also strongly recommend using an inner-frame inside the space-frame, which provides some helpful CSS to make things centered both vertically and horizontally inside the frame.

<div class="space-frame">
    <section class="space-inner-frame">
        [contents]
    </section>
</div>

Custom duration

If we want we can provide a custom duration for our frames with the data-duration attribute, which multiplies the default duration of the transition.
<section class="space-frame" data-duration="1.4">...</section>
<section class="space-frame" data-duration="0.6">...</section>

Options

Space.js has a default default transition - which is to enter by fading in and exit by scaling up and fading out. We can also provide a custom transition override to the library from predefined transitions. (We can also create our own transitions from scratch, but we'll get to that later.)
<section class="space-frame" data-transition="rotate360">...</section>
Multiple values are supported!

<section class="space-frame" data-transition="rotate360 fadeOut slideInLeft">...</section>

Custom entry and exit

If we really want to get into detail, we can provide how we wish the frame to enter (first half of the frame duration) and exit (second half).
<section class="space-frame" data-enter="fadeIn" data-exit="fadeOut zoomOut">...</section>

What a complete frame could look like


<div class="space-frame" data-enter="fadeIn" data-exit="zoomOut fadeOut" data-duration="1.3">
    <section class="space-inner-frame">
        <div style="background-image:url(img/splash.png); padding:150px 200px;" class="bg">
            <section>
                <p>Demo 1</p>
                <h1>The Gallery</h1>
            </section>
        </div>
    </section>
</div>

Custom transitions

You can add your own transitions with the `addTransitions method. Make sure it is done after the library is loaded.
<script src="space.js"></script>

<script type="text/javascript">
    var transitions = {
        rotate720: {
            'rotate':{from:0, to:720}
        },
        fadeOutHalf: {
            'opacity':{from:1, to:0.5}
        }
    };
    Space.addTransitions(transitions);
</script>

Currently supported transitions

Note that these might come to change during the beta-phase of the library.
  • scaleIn
  • fadeIn
  • scaleOut
  • fadeOut
  • rotateQuarterRight
  • rotateInQuarterClockwise
  • zoomOut
  • slideInBottom
  • slideOutDown
  • slideOutLeft
  • slideOutRight
  • slideInRight
  • slideOutUp
  • slideInTop
  • slideInLeft
  • slideBottomRight
  • rotate360
  • rotate3dOut






... [Your contents]