Skip to content

Latest commit

 

History

History
699 lines (515 loc) · 13.1 KB

javascript.md

File metadata and controls

699 lines (515 loc) · 13.1 KB

JavaScript Style Guide

A reasonable style guide for modern JavaScript development.

  1. Objects
  2. Arrays
  3. Strings
  4. Functions
  5. Properties
  6. Variables
  7. Layout
  8. Conditional Evaluation
  9. Blocks
  10. Whitespace
  11. Leading Commas
  12. Semicolons
  13. Naming Conventions
  14. Comments
  15. jQuery
  16. Resources
  17. License

"All code in any code-base should look like a single person typed it, no matter how many people contributed."

idiomatic.js

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: 'superman',
    defaults: { clark: 'kent' },
    hidden: true
};

[⬆]

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.

var len = items.length,
    itemsCopy = [],
    i;

// Bad
for (i = 0; i < len; i++) {
    itemsCopy[i] = items[i];
}

// Good
itemsCopy = Array.prototype.slice.call(items);

[⬆]

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.

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

// 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 precendence 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 luke = {
    jedi: true,
    age: 28
};

function getProp(prop) {
    return luke[prop];
}

var isJedi = getProp('jedi');

[⬆]

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 and declare each variable on a newline.

// Bad
var items = getItems();
var goSportsTeam = true;
var drangonball = 'z';

// Good
var items = getItems(),
    goSportsTeam = true,
    drangonball = 'z';

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

[⬆]

All JavaScript written by both front and back end developers is laid out in the same pattern to ensure that it is easy to quickly identify the purpose of the file. A standard .js file should use the following format:

var tangent = window.tangent || {};
    tangent.feedback = {
        init: function() {
            chameleon.feedback.setupSomeThing();
        }

        setupSometThing: function() {
            // Set up the thing
        }
    }

    $.ready(function() {
        tangent.feedback.init();
    });

The purpose here is two-fold. Firstly it places all non-private functions in the same scope, making them easy to access and secondly, because at a glance any developer can see what the purpose of the JS in the file is (as long as functions are properly names). It is also a neat layout and encourages consistently throughout.

[⬆]

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

Use shortcuts

// Bad
if (name !== '') {
    // ...stuff...
}

// Good
if (name) {
    // ...stuff...
}

// Bad
if (collection.length > 0) {
    // ...stuff...
}

// Good
if (collection.length) {
    // ...stuff...
}

[⬆]

Use braces with all multi-line blocks.

// Bad
if (test)
    return false;

// Good
if (test) {
    return false;
}

// Bad
function() { return false; }

// Good
function() {
    return false;
}

[⬆]

Use soft tabs set to 4 spaces.

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

Place an empty newline at the end of the file.

// Bad
(function(global) {
    // ...stuff...
})(this);
// Good
(function(global) {
    // ...stuff...
})(this);

[⬆]

Nope.

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

[⬆]

Yup.

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

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

[⬆]

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 = {};
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 // 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;
}

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

[⬆]

Prefix jQuery object variables with a $.

// Bad
var container = $('#container');

// Good
var $container = $('#container');

Cache jQuery lookups.

// Bad
function setContainer() {
    $('#container').hide();

    // ...stuff...

    $('#container').show();
}

// Good
function setContainer() {
    var $container = $('#container');

    $container.hide();

    // ...stuff...

    $container.show();
}

[⬆]

The Spec

Books

Blogs

Tutorials

Other Styleguides

[⬆]

(The MIT License)

Copyright (c) 2012 Nathan Staines

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.

[⬆]