Skip to content

Instantly share code, notes, and snippets.

@carlosdelfino
Forked from fnando/gist:2420869
Created April 23, 2012 20:28
Show Gist options
  • Save carlosdelfino/2473612 to your computer and use it in GitHub Desktop.
Save carlosdelfino/2473612 to your computer and use it in GitHub Desktop.
My JavaScript Guidelines

JavaScript

Semicolon

I use it. If you don't, read these:

You can still ignore semicolons, but know that ASI is a syntactic error correction procedure, according to Brendan Eich himself.

Whitespaces

  • Never mix tabs or spaces.
  • Prefer spaces over hard tabs for indentation (I recommend 2 spaces).
  • Eliminate end of line whitespace.
  • Eliminate blank line whitespace.
  • Too much space and no space at all are equally bad.

Naming

  • Use camelCase for variables.
  • Contructor functions must start with capital letter like ModalWindow.
  • Avoid names like handler, data, or other generic words.
  • Don't even think about using Hungarian notation.

Quotes

Choose between single or double quotes, but don't mix different quote types in the same project.

Parens, Braces, Linebreaks

// Add whitespace around parens and braces,
// but not around arguments.
if (something) {
  doSomething();
}

if (something) {
  doSomething();
} else {
  doSomethingElse();
}

// Again, no spaces around arguments.
while (condition) {
  doSomething();
}

// The whitespace balance.
for (var i = 0; i < 100; i++) {
  doSomething();
}

Assignments, Declarations, Functions

// Variables
var name = "John Doe"
  , email = "[email protected]"
  , status
;

// Literal notation
var array = []
  , object = {}
;

// Object attributes
var object = {
    name: "John Doe"
  , email: "[email protected]"
  , status: null
};

// Named and assigned functions
function hello() {
  doSomething();
}

var hello = function() {
  doSomething();
};

// Argument declaration
function hello(message, name, callback) {
  doSomething();
}

// Executing functions
// -------------------
//
// Callbacks must ignore spaces around parens and braces
hello("Hi there", "John Doe", function(){
  doSomethingElse();
});

Comparison

Use === and !== wherever is possible.

General

Short-circuit functions increase readability

function something(arg) {
  var result;

  if (!arg) {
    return;
  }

  result = doSomething();
  result = doSomethingElse(result);

  return result;
}

Boolean return

Don't use ifs to return a boolean. So instead of doing

function greater(a, b) {
  if (a > b) {
    return true;
  } else {
    return false;
  }
}

return the expression itself.

function greater(a, b) {
  return a > b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment