Skip to content

Instantly share code, notes, and snippets.

@sh0bh1t
Created August 11, 2016 07:48
Show Gist options
  • Select an option

  • Save sh0bh1t/fff729b605e70a6c1d325443b5305d75 to your computer and use it in GitHub Desktop.

Select an option

Save sh0bh1t/fff729b605e70a6c1d325443b5305d75 to your computer and use it in GitHub Desktop.
JavaScript coding style

tl;dr

Your JS code should look like this:

/**
 * Recursive function to compute Fibonacci numbers
 *
 * @param {number} n
 * @return {number}
 */
var fibonacciNumber = function(n) {
    var MIN = 0;

    if (n < MIN) {
        return MIN;
    }

    if (n < 2) {
        return n;
    }

    return fibonacciNumber(n - 1) + fibonacciNumber(n - 2);
};

Coding Style

Based on: http://nodeguide.com/style.html, http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml and http://javascript.crockford.com/code.html

Code Analytics We use JSHint for code analytics.

Documentations All files, classes, methods and properties should be documented with JSDoc comments with the appropriate tags and types.

More about JSDoc: http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Comments#Comments

Tabs vs Spaces Use 4 space!

Trailing whitespace Just like you brush your teeth after every meal, you clean up any trailing whitespace in your JavaScript files before committing. Otherwise the rotten smell of careless neglect will eventually drive away contributors and/or co-workers.

Line length Limit your lines to 80 characters. Yes, screens have gotten much bigger over the last few years, but your brain hasn't. Use the additional room for split screen, your editor supports that, right?

Place the break after an operator, ideally after a comma. A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion.

if statement The if class of statements should have the following form:

if (condition) {
    statements
}

if (condition) {
    statements
} else {
    statements
}

if (condition) {
    statements
} else if (condition) {
    statements
} else {
    statements
}

for statement A for class of statements should have the following form:

for (initialization; condition; update) {
    statements
}

for (variable in object) {
    if (filter) {
        statements
    }
}

The first form should be used with arrays and with loops of a predeterminable number of iterations.

The second form should be used with objects. Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object:

for (variable in object) {
    if (object.hasOwnProperty(variable)) {
        statements
    }
}

while statement A while statement should have the following form:

while (condition) {
    statements
}

do statement A do statement should have the following form:

do {
    statements
} while (condition);

Unlike the other compound statements, the do statement always ends with a ; (semicolon).

switch statement A switch statement should have the following form:

switch (expression) {
case expression:
    statements
default:
    statements
}

Each case is aligned with the switch. This avoids over-indentation.

Each group of statements (except the default) should end with break, return, or throw. Do not fall through.

try statement The try class of statements should have the following form:

try {
    statements
} catch (variable) {
    statements
}

try {
    statements
} catch (variable) {
    statements
} finally {
    statements
}

Variable and property names Variables and properties should use lower camel case capitalization. They should also be descriptive. Single character variables and uncommon abbreviations should generally be avoided.

Right:

var adminUser = db.query('SELECT * FROM users ...');

Wrong:

var admin_user = d.query('SELECT * FROM users ...');

Array and Object Initializers Single-line array and object initializers are allowed when they fit on a line.

Long identifiers or values present problems for aligned initialization lists, so always prefer non-aligned initialization.

Right:

CORRECT_Object.prototype = {
  a: 0,
  b: 1,
  lengthyName: 2
};

Wrong:

WRONG_Object.prototype = {
  a          : 0,
  b          : 1,
  lengthyName: 2
};

Function Arguments When possible, all function arguments should be listed on the same line. If doing so would exceed the 80-column limit, the arguments must be line-wrapped in a readable way:

veryLongFunctionName(
    veryLongArgumentNameA, veryLongArgumentNameB, veryLongArgumentNameC
) {
    // ...
}
veryLongFunctionName(
    veryLongArgumentNameA,
    veryLongArgumentNameB,
    veryLongArgumentNameC,
    veryLongArgumentNameD
) {
    // ...
}

Whitespace Blank lines improve readability by setting off sections of code that are logically related.

doSomethingTo(x);
doSomethingElseTo(x);
andThen(x);

nowDoSomethingWith(y);

andNowWith(z);

Blank spaces should be used in the following circumstances:

  • A keyword followed by ( (left parenthesis) should be separated by a space. while (true) {
  • A blank space should not be used between a function value and its ( (left parenthesis). This helps to distinguish between keywords and function invocations.
  • All binary operators except . (period) and ( (left parenthesis) and [ (left bracket) should be separated from their operands by a space.
  • No space should separate a unary operator and its operand except when the operator is a word such as typeof.
  • Each ; (semicolon) in the control part of a for statement should be followed with a space.
  • Whitespace should follow every , (comma).

Semicolons Use semicolons!

Comments Make comments meaningful. Focus on what is not immediately visible. Generally use line comments. Save block comments for formal documentation and for commenting out.

Quotes Use single quotes, unless you are writing JSON.

Assignment Expressions Avoid doing assignments in the condition part of if and while statements.

Variable declarations Always declarate with var! Declare one variable per var statement, it makes it easier to re-order the lines.

Right:

var keys = [ 'foo', 'bar' ];
var values = [ 23, 42 ];

Wrong:

var keys = [ 'foo', 'bar' ],
    values = [ 23, 42 ],
    object = {},
    key;

All variables should be declared before used. JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that may become implied globals. Implied global variables should never be used.

The var statements should be the first statements in the function body.

There's no reason to use wrapper objects for primitive types, plus they're dangerous:

var x = new Boolean(false);
if (x) {
  alert('hi');  // Shows 'hi'.
}

Don't do it!

No multiline string literals, like this:

var a = 'lorem \
         ipsum';

Function declarations No function declaration within blocks.

Right:

if (x) {
  var foo = function() {};
}

Wrong:

if (x) {
  function foo() {}
}

If a function literal is anonymous, there should be one space between the word function and the ( (left parenthesis). If the space is omited, then it can appear that the function's name is function, which is an incorrect reading.

Use of global functions should be minimized.

When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

Function length Keep your functions short. A good function fits on a slide that the people in the last row of a big room can comfortably read. So don't count on them having perfect vision and limit yourself to ~10 lines of code per function.

Return statements To avoid deep nesting of if-statements, always return a functions value as early as possible.

Right:

function isPercentage(val) {
  if (val < 0) {
    return false;
  }

  if (val > 100) {
    return false;
  }

  return true;
}

Wrong:

function isPercentage(val) {
  if (val >= 0) {
    if (val < 100) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

Labels Statement labels are optional. Only these statements should be labeled: while, do, for, switch.

Class names Class names should be capitalized using upper camel case.

Right:

function BankAccount() { }

Wrong:

function bank_Account() { }

Constants Constants should be declared as regular variables or static class properties, using all uppercase letters.

Node.js / V8 actually supports mozilla's const extension, but unfortunately that cannot be applied to class members, nor is it part of any ECMA standard.

Right:

var SECOND = 1 * 1000;

Wrong:

const SECOND = 1 * 1000;

Object / Array creation Use arrays when the member names would be sequential integers. Use objects when the member names are arbitrary strings or names.

Use Array and Object literals instead of Array and Object constructors. Don't use trailing commas. Put short declarations on a single line. Only quote keys when your interpreter complains:

Right:

var a = [ 'hello', 'world' ];
var b = {
  good: 'code',
  'is generally': 'pretty'
};

Wrong:

var a = [
  'hello', 'world'
];
var b = {"good": 'code'
        , is generally: 'pretty',
        };

Equality operator Use the triple equality operator!

Right:

var a = 0;
if (a === '') {
  console.log('winning');
}

Wrong:

var a = 0;
if (a == '') {
  console.log('losing');
}

For type casting:

if (!a) {
    // ...
}

Extending prototypes Do not extend the prototypes of any objects, especially native ones. There is a special place in hell waiting for you if you don't obey this rule.

Conditions Any non-trivial conditions should be assigned to a descriptive variable:

Right:

var isAuthorized = (user.isAdmin() || user.isModerator());
if (isAuthorized) {
  console.log('winning');
}

Wrong:

if (user.isAdmin() || user.isModerator()) {
  console.log('losing');
}

Object.freeze, Object.preventExtensions, Object.seal, with, eval Crazy shit that you will probably never need. Stay away from it.

Getters and setters Do not use setters, they cause more problems for people who try to use your software than they can solve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment