Skip to content

Instantly share code, notes, and snippets.

@lucascaton
Forked from fnando/gist:2420869
Created April 19, 2012 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucascaton/2420977 to your computer and use it in GitHub Desktop.
Save lucascaton/2420977 to your computer and use it in GitHub Desktop.
My JavaScript Guidelines

JavaScript

These are the JavaScript rules I've been living by and don't expect you to agree or follow them.

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 = "john@example.org"
  , status
;

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

// 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment