JavaScript Coding Style

From Code Self Study Wiki
Jump to: navigation, search

This is a draft with some ideas on JavaScript coding styles. The code itself is not intended to do anything coherent. See Douglas Crockford's code conventions and jscode.org for more ideas.

Indentation[edit]

Should be four spaces, because it's easier to read. Python and PHP both officially recommend four-space indentation.

Good:

function doSomething(a, b) {
    if (a < b) {
        return a + b;
    } else {
        return a * b;
    }
}

This way takes more effort to see the indentations and is not as easy to read:

function doSomething(a, b) {
  if (a < b) {
    return a + b;
  } else {
    return a * b;
  }
}

Double or Single Quotes[edit]

Use single quotes, except in cases where it makes it more readable to use double quotes for the outer quotes. [Still debating this.] JSON, HTML, and CSS should use double quotes.

This is good:

$('#theButton').fadeIn();
var person = {
    'name': 'Bob',
    'age': 25
}

This is good:

var html = '<a href="http://example.com">Example</a>';

Don't do this, if it can be avoided:

var html = "<a href=\"http://example.com\">Example</a>";

Curly Braces[edit]

They are not optional and they should go on the same line as the statement. Using new lines isn't correct in JavaScript.

Correct:

function doSomething(a) {
    // Do something
}

This style is not correct in JavaScript and it will cause an error in some cases:

function doSomething(a)
{
    // Do something
}

For example, this will produce an error in JavaScript due to semicolon insertion by the interpreter:

return
{
    alertMsg: function (msg) { alert(msg) },
    consoleMsg: function (msg) { console.log(msg) }
}

Anonymous Function Names[edit]

The function has no name. The name of the function is not "function". Therefore put a space after it.

Correct -- note the spaces after the word, function, and after the arguments:

var doSomething = function (a, b) {
    // Do something
}

This makes less sense to me:

var doSomething = function(a, b){
    // Do something
}

This is how a named function would be written:

function f(x) {
    // Do something
}

Remove the function name (but not the space) and you get an anonymous function:

function (x) {
    // Do something
}

You aren't calling the keyword function, you're calling a function that has no name -- just a blank space.

If Statements[edit]

Note the spaces:

if (a < b) {
    // Do something
} else {
    // Do something else
}

Semicolons[edit]

Not optional.

Case[edit]

  • JavaScript variables: camelCase.
  • CSS IDs: camelCase
  • CSS classes: dashes-like-this

For Loops[edit]

Cache the length for performance. All operators have a space, so ++ should too. [I changed my mind about that.]

for (var i, len = thing.length; i < len; i++) {
    console.log(thing[i]);
}