Archive for December, 2012

JavaScript Coding Standards and Guidelines

December 19, 2012

This is the current set of coding standards and guidelines I use when I’m coding in the JavaScript language.
I thought it would be good to share so others could get use out of them also, and maybe start a discussion as to amendments / changes they see that could be useful?

Naming Conventions

Names should be formed from the 26 upper and lower case letters (A .. Z, a .. z), the 10 digits (0 .. 9), and _ (underbar).
Avoid use of international characters because they may not read well or be understood everywhere.
Do not use $ (dollar sign) or \ (backslash) in names.

I think jQuery would have to be an exception to this

Do not use _ (underbar) as the first character of a name.
It is sometimes used to indicate privacy, but it does not actually provide privacy.
If privacy is important, use the forms that provide private members.

Most variables and functions should start with a lower case letter.

Constructor functions which must be used with the new prefix should start with a capital letter.
JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted.
Bad things can happen if new is not used, so the capitalization convention is the only defence we have.

Global variables should be in all caps.
JavaScript does not have macros or constants, so there isn’t much point in using all caps to signify features that JavaScript doesn’t have.
Same with Enum names. There is no native ability to create constant variables. Although… you can create read-only properties.
With the advent of ES5 we now have a couple of well known techniques to enforce that our property values can not be altered once initialised.

When you define a property using one of the ES5 techniques, (1) when you set the writable property attribute to false the value of the value attribute can no longer be altered. (2) Using an accessor property with only a get function

var objWithMultipleProperties;
var objWithMultiplePropertiesDescriptor;

objWithMultipleProperties = Object.defineProperties({}, {
   x: { value: 1, writable: true, enumerable:true, configurable:true }, // Change writable to false enables read-only semantics.
   y: { value: 1, writable: true, enumerable:true, configurable:true }, // Change writable to false enables read-only semantics.
   r: {
      get: function() {
         return Math.sqrt(this.x*this.x + this.y*this.y)
      },
      enumerable:true,
      configurable:true
   }
});

objWithMultiplePropertiesDescriptor = Object.getOwnPropertyDescriptor(objWithMultipleProperties, 'r');
// objWithMultiplePropertiesDescriptor {
//    configurable: true,
//    enumerable: true,
//    get: function () {
//       // other members in here
//    },
//    set: undefined,
//   // ...
// }

See here for complete coverage of property attributes.

Coding Style

Commenting

Use comments where needed.

If the script needs commenting due to complexity, consider revising before commenting.
Comments easily rot (can be left behind after future code changes).
It is important that comments be kept up-to-date. Erroneous comments can make programs even harder to read and understand.
In this case they cause more damage than they originally gave benefit.
Comments should be well-written and clear, just like the code they are annotating.

Make comments meaningful. Focus on what is not immediately visible. Don’t waste the reader’s time with stuff like

i = 0; // Set i to zero.

Comment Style

Block comments are not safe for
commenting out blocks of code. For example:

/*
var rm_a = /a*/.match(s);
*/

causes a syntax error. So, it is recommended that /* */ comments be avoided and //
comments be used instead.

Don’t use HTML comments in script blocks. In the ancient days of javascript (1995), some browsers like Netscape 1.0 didn’t have any support or knowledge of the script tag. So when javascript was first released, a technique was needed to hide the code from older browsers so they wouldn’t show it as text in the page. The ‘hack’ was to use HTML comments within the script block to hide the code.

<script language="javascript">
<!--
   // code here
   //-->
</script>

No browsers in common use today are ignorant of the <script> tag, so hiding of javascript source is no longer necessary. Thanks Matt Kruse for re-iterating this.

File Organization

JavaScript programs should be stored in and delivered as .js files.

  • JavaScript should not be in HTML
  • JavaScript should not be in CSS
  • CSS should not be in JavaScript
  • HTML should not be in JavaScript

Code in HTML adds significantly to page weight with no opportunity for mitigation by caching and compression. There are many other reasons to keep the UI layers separate.

<script src=filename.js>; tags should be placed as late in the body as possible.
This reduces the effects of delays imposed by script loading on other page components.

There is no need to use the language or type attributes. It is the server, not the script tag, that determines the MIME type.

Formatting

Bracing

Use same line opening brace.
Brace positioning is more or less a holy war without any right answer — except in JavaScript, where same-line braces are right and you should always use them. Here’s why:

return
{
  ok: false;
};

return {
  ok: true;
};

What’s the difference between these two snippets? Well, in the first one, you silently get something completely different than what you wanted.
The lone return gets mangled by the semicolon insertion process and becomes return; and returns nothing.
The rest of the code becomes a plain old block statement, with ok: becoming a label (of all things)! Having a label there might make sense in C, where you can goto, but in JavaScript, it makes no sense in this context.
And what happens to false? it gets evaluated and completely ignored.
Finally, the trailing semicolon — what about that?
Do we at least get a syntax error there? Nope: empty statement, like in C.

Spacing

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

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

Tabs and Indenting

The unit of indentation is three spaces.
Use of tabs should be avoided because (as of this writing in the 21st Century) there still is not a standard for the placement of tab stops.
The use of spaces can produce a larger file size, but the size is not significant over local networks, and the difference is eliminated by minification.

Line Length

Avoid lines longer than 80 characters. When a statement will not fit on a single line, it may be necessary to break it.
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.
The next line should be indented six spaces.

Language Usage

Access To Members

In JavaScript we don’t have access modifiers like we do in classical languages.

In saying that, we can and should still control the accessibility of our members, and keep as much of our objects information secret to outsiders.
We can apply public, private and Privileged access.

public

Members created in the Constructor using the dot notation

function Container(param) {
    this.member = param;
}

So, if we construct a new object

var myContainer = new Container('abc');

then myContainer.member contains 'abc'.

In the prototype we can add a public method.
To add a public method to all objects made by a constructor, add a function to the constructor’s prototype:

Container.prototype.stamp = function (string) {
    return this.member + string;
}

We can then invoke the method

myContainer.stamp('def')

which produces 'abcdef'.

private

Ordinary vars and parameters of the constructor becomes the private members

function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}

param, secret, and that are private member variables.
They are not accessible to the outside.
They are not even accessible to the objects own public methods.

They are accessible to private methods
Private methods are inner functions of the constructor.

function Container(param) {

    this.member = param; // param is private, member is public
    var secret = 3;      // secret is private
    var that = this;     // that is private
    function dec() {     // dec is private
        var innerFunction = function () {
            that.value = someCrazyValue;  // when dec is called, value will be a member of the newly constructed Container instance.
        };

        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }
}

A method (which is a function that belongs to an object) cannot employ an inner function to help it do its work because the inner function does not
share the method’s access to the object as its this is bound to the global object. This was a mistake in the design of the language.
Had the language been designed correctly, when the inner function is invoked, this would still be bound to the this variable of the outer function.
The work around for this is to define a variable and assign it the value of this.
By convention, the name of that variable I use is that.

  • Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.
privileged

A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.

Privileged methods are assigned with this within the constructor.

function Container(param) {

    this.member = param;
    var secret = 3;
    var that = this;

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.service = function () { // prefix with this to assign a function to be a privileged method
        if (dec()) {
            return that.member;
        } else {
            return null;
        }
    };
}

service is a privileged method. Calling myContainer.service() will return 'abc' the first three times it is called. After that, it will return null. service calls the private dec method which accesses the private secret variable. service is available to other objects and methods, but it does not allow direct access to the private members.

eval is Evil

The eval function is the most misused feature of JavaScript. Avoid it.
eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or setInterval.

Global Abatement

JavaScript makes it easy to define global variables that can hold all of the assets of your application.
Unfortunately, global variables weaken the resiliency of programs and should be avoided.

One way to minimize the use of global variables is to create a single global variable
for your application:

var KimsGlobal = {};

That variable then becomes the container for your application:

KimsGlobal.Calculate = {
    calculatorOutPutArray: [
    $('.step1i1'),
    $('.step1i2'),
    $('.step1r1'),
    ...
    ],
    jQueryObjectCounter: 0,
    jQueryDOMElementCounter: 0
    ...
};

KimsGlobal.NavigateCalculator = {
    currentStepId: stepId,
    step: 'step' + stepId,
    stepSelector: = '#' + step,
    ...
};

By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries.
Your program also becomes easier to read because it is obvious that KimsGlobal.Calculate refers to a top-level structure.

Using closure for information hiding is another effective global abatement technique.

var digit_name = (function() {
  var names = ['zero', 'one', 'two', ...];
  return function (n) {
    return names[n];
  };
})();

Using the Module patterns explains this in detail.

Scoping

JavaScript scoping is different to classical languages, and can take some getting used to for programmers used to languages such as C, C++, C#, Java.
Classical languages like the before mentioned have block scope.
JavaScript has function scope. Although ES6 is bringing in block scoping with the let keyword.

In the following example “10” will be alerted.
var foo = 1; // foo is defined in global scope.
function bar() {
    if (!foo) { // The foo variable of the bar scope has been hoisted directly above this if statement, but the assignment has not. So it is unassigned (undefined).
        var foo = 10;
    }
    alert(foo);
}
bar();
In the following example “1” will be alerted.
var a = 1;
function b() {
    a = 10;
    return;
    function a() {}
}
b();
alert(a);
In the following example Firebug will show 1, 2, 2.
var x = 1;
console.log(x); // 1
if (true) {
    var x = 2;
    console.log(x); // 2
}
console.log(x); // 2

In JavaScript, blocks such as if statements, do not create new scope. Only functions create new scope.

There is a workaround though 😉
JavaScript has Closure.
If you need to create a temporary scope within a function, do the following.

function foo() {
    var x = 1;
    if (x) {
        (function () {
            var x = 2;
            // some other code
        }());
    }
    // x is still 1.
}

Line 3: begins a closure
Line 6: the closure invokes itself with ()

Hoisting

Terminology

function declaration or function statement are the same thing.
function expression or variable declaration with function assignment are the same thing.

A function statement looks like the following:

function foo( ) {}

A function expression looks like the following:

var foo = function foo( ) {};

A function expression must not start with the word “function”.

//anonymous function expression
var a = function () {
    return 3;
}

//named function expression
var a = function bar() {
    return 3;
}

//self invoking named function expression. This is also a closure
(function sayHello() {
    alert('hello!');
})();

//self invoking anonymous function expression. This is also a closure
(function ( ) {
    var hidden_variable;
    // This function can have some impact on
    // the environment, but introduces no new
    // global variables.
}() );

In JavaScript, a name enters a scope in one of four basic ways:

  1. Language-defined: All scopes are, by default, given the names this and arguments.
  2. Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function.
  3. Function declarations: These are of the form function foo() {}.
  4. Variable declarations: These take the form var foo;.

Function declarations and variable declarations are always hoisted invisibly to the top of their containing scope by the JavaScript interpreter.
Function parameters and language-defined names are, obviously, already there. This means that code like this:

function foo() {
    bar();
    var x = 1;
}

Is actually interpreted like this:

function foo() {
    var x;
    bar();
    x = 1;
}

It turns out that it doesn’t matter whether the line that contains the declaration would ever be executed. The following two functions are equivalent:

function foo() {
    if (false) {
        var x = 1;
    }
    return;
    var y = 1;
}
function foo() {
    var x, y;
    if (false) {
        x = 1;
    }
    return;
    y = 1;
}

The assignment portion of the declaration is not hoisted.
Only the identifier is hoisted.
This is not the case with function declarations, where the entire function body will be hoisted as well,
but remember that there are two normal ways to declare functions. Consider the following JavaScript:

function test() {
    foo(); // TypeError 'foo is not a function'
    bar(); // 'this will run!'
    var foo = function () { // function expression assigned to local variable 'foo'
        alert('this won't run!');
    }
    function bar() { // function declaration, given the name 'bar'
        alert('this will run!');
    }
}
test();

In this case, only the function declaration has its body hoisted to the top. The name ‘foo’ is hoisted, but the body is left behind, to be assigned during execution.

Name Resolution Order

The most important special case to keep in mind is name resolution order. Remember that there are four ways for names to enter a given scope. The order I listed them above is the order they are resolved in. In general, if a name has already been defined, it is never overridden by another property of the same name. This means that a function declaration takes priority over a variable declaration. This does not mean that an assignment to that name will not work, just that the declaration portion will be ignored. There are a few exceptions:

  • The built-in name arguments behaves oddly. It seems to be declared following the formal parameters, but before function declarations. This means that a formal parameter with the name arguments will take precedence over the built-in, even if it is undefined. This is a bad feature. Don’t use the name arguments as a formal parameter.
  • Trying to use the name this as an identifier anywhere will cause a Syntax Error. This is a good feature.
  • If multiple formal parameters have the same name, the one occurring latest in the list will take precedence, even if it is undefined.

Additional hoisting examples on my blog

Now that you understand scoping and hoisting, what does that mean for coding in JavaScript?
The most important thing is to always declare your variables with var statements.
Declare your variables at the top of the scope (as already mentioned JavaScript only has function scope). See the Variable Declarations section.
If you force yourself to do this, you will never have hoisting-related confusion.
However, doing this can make it hard to keep track of which variables have actually been declared in the current scope.
I recommend using strict mode which will inform you if you have tried to use a variable without declaring it with var. If you’ve done all of this, your code should look something like this:

function foo(a, b, c) {
    'use strict';
    var x = 1;
    var bar;
    var baz = 'something';
    // other non hoistable code here
}

Inheritance

Always prefer Prototypal inheritance to Pseudo classical.

There are quite a few reasons why we shouldn’t use Pseudo classical inheritance in JavaScript.
JavaScript The Good Parts explains why.

In a purely prototypal pattern, we dispense with classes.
We focus instead on the objects.
Prototypal inheritance is conceptually simpler than classical inheritance.

I’ll show you three examples of prototypal inheritance, and explain the flaws and why the third attempt is the better way.

Example 1
function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

The object function takes an existing object as a parameter and returns an empty new object that inherits from the old one.
The problem with the object function is that it is global, and globals are clearly problematic.

Example 2
Object.prototype.begetObject = function () {
    function F() {}
    F.prototype = this;
    return new F();
};

newObject = oldObject.begetObject();

The problem with Object.prototype.begetObject is that it trips up incompetent programs, and it can produce unexpected results when begetObject is overridden.

Example 3
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);

Example 3 overcomes the problems with the previous prototypical examples.
This is how Object.create works in ES5

New

Use {} instead of new Object(). Use [] instead of new Array(). There are instances where using new allows compiler optimisations to be performed. Learn what happens when you use new in different scenarios and test.

Operators

Plus Minus

Be careful to not follow a + with + or ++. This pattern can be confusing. Insert parens between them to make your intention clear.

total = subtotal + +myInput.value;

is better written as

total = subtotal + (+myInput.value);

so that the + + is not misread as ++.

Equality
By default use the === operator rather than the == operator.
By default use the !== operator rather than the != operator.

JavaScript has two sets of equality operators: === and !==, and their (as Douglas Crockford puts it) evil twins == and
!=. The === and !== ones work the way you would expect. If the two operands are of the
same type and have the same value, then === produces true and !== produces false.
The other ones do the right thing when the operands are of the same type, but if they
are of different types, they attempt to coerce the values.
Make sure this is what you need rather than just blindly using the shorter form.
These are some of the interesting cases:

'' == '0'          // false
0 == ''            // true
0 == '0'           // true
false == 'false'   // false
false == '0'       // true
false == undefined // false
false == null      // false
null == undefined  // true
' \t\r\n ' == 0    // true

Patterns

Module

Module presents an interface but hides its state and implementation.
Takes advantage of function scope and closure to create relationships that are binding and private.
Eliminate the use of global variables. It promotes information hiding and other good design practices.

Global Import

JavaScript has a feature known as implied globals.
Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name.
If none is found, that variable is assumed to be global.
If it’s used in an assignment, the global is created if it doesn’t already exist.
This means that using or creating global variables in an anonymous closure is easy.
Unfortunately, this leads to hard-to-manage code, as it’s not obvious (to humans) which variables are global in a given file.

Luckily, our anonymous function provides an easy alternative.
By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals.

(function ($, YAHOO) {
    // now have access to globals jQuery (as $) and YAHOO in this code
}(jQuery, YAHOO));
Module Export

Sometimes you don’t just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function’s return value.

var MODULE = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

Notice that we’ve declared a global module named MODULE, with two public properties:
a method named MODULE.moduleMethodand a variable named MODULE.moduleProperty.
In addition, it maintains private internal state using the closure of the anonymous function.
Also, we can easily import needed globals, using the pattern we learned above.

Augmentation

One limitation of the module pattern so far is that the entire module must be in one file.
Anyone who has worked in a large code-base understands the value of splitting among multiple files.
Luckily, we have a nice solution to augment modules.
First, we import the module, then we add properties, then we export it.
Here’s an example, augmenting our MODULE from above:

var MODULE = (function (my) {
    my.anotherMethod = function () {
        // added method...
    };

    return my;
}(MODULE));

Use the var keyword again.
After this code has run, our module will have gained a new public method named MODULE.anotherMethod.
This augmentation file will also maintain its own private internal state and imports.

Loose Augmentation

While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn’t always necessary.
One of the best things a JavaScript application can do for performance is to load scripts asynchronously.
We can create flexible multi-part modules that can load themselves in any order with loose augmentation.
Each file should have the following structure:

var MODULE = (function (my) {
    // add capabilities...

    return my;
}(MODULE || {}));

The import will create the module if it doesn’t already exist.
This means you can use a library like require.js and load all of your module files in parallel, without needing to block.
preferably not more than 2 to 3 at a time, else performance will degrade

Tight Augmentation

While loose augmentation is great, it does place some limitations on your module.
Most importantly, you cannot override module properties safely.
You also cannot use module properties from other files during initialization (but you can at run-time after intialization).
Tight augmentation implies a set loading order, but allows overrides.
Here is a simple example (augmenting our original MODULE):

var MODULE = (function (my) {
    var old_moduleMethod = my.moduleMethod;

    my.moduleMethod = function () {
        // method override, has access to old through old_moduleMethod...
    };

    return my;
}(MODULE));

Here we’ve overridden MODULE.moduleMethod, but maintain a reference to the original method, if needed.

Cloning and Inheritance
var MODULE_TWO = (function (old) {
    var my = {},
    var key;

    for (key in old) {
        if (old.hasOwnProperty(key)) {
            my[key] = old[key];
        }
    }

    var super_moduleMethod = old.moduleMethod;
    my.moduleMethod = function () {
        // override method on the clone, access to super through super_moduleMethod
    };

    return my;
}(MODULE));

This pattern is perhaps the least flexible option. It does allow some neat compositions, but that comes at the expense of flexibility.
As I’ve written it, properties which are objects or functions will not be duplicated, they will exist as one object with two references.
Changing one will change the other.
This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with eval.

Sub-modules
MODULE.sub = (function () {
    var my = {};
    // ...

    return my;
}());

Statements

Simple Statements

Each line should contain at most one statement.
Put a ; (semicolon) at the end of every simple statement.
Note that an assignment statement which is assigning a function literal or object literal is still an assignment statement and must end with a semicolon.

JavaScript allows any expression to be used as a statement.
This can mask some errors, particularly in the presence of semicolon insertion.
The only expressions that should be used as statements are assignments and invocations.

Compound Statements

Compound statements are statements that contain lists of statements enclosed in { } (curly braces).

  • The enclosed statements should be indented four more spaces.
  • The { (left curly brace) should be at the end of the line that begins the compound statement.
  • The } (right curly brace) should begin a line and be indented to align with the beginning of the line containing the matching { (left curly brace).
  • Braces should be used around all statements, even single statements, when they are part of a control structure, such as an if or for statement. This makes it easier to add statements without accidentally introducing bugs.
Labels
Say no to labelling Statement labels are optional. Only these statements should be labelled: while, do, for, switch. Or better still don’t use labelling.
return Statement

A return statement with a value should not use ( ) (parentheses) around the value.
The return value expression must start on the same line as the return keyword in order to avoid 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
}

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

Is

if (a = b) {

a correct statement? Or was

if (a === b) {

intended? Avoid constructs that cannot easily be determined to be correct.

Also see the Equality section

for Statement

A for class of statements should have the following form:

for (initialisation; condition; update) {
    statements
}

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

The first form should be used with arrays and with loops of a predetermined 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.

Or better, use the following form from Angus Crolls blog post

Procedural way to do the construct

var whatToBring;
switch(weather) {
    case 'Sunny':
        whatToBring = 'Sunscreen and hat';
        break;
    case 'Rain':
        whatToBring  ='Umbrella and boots';
        break;
    case 'Cold':
        whatToBring = 'Scarf and Gloves';
        break;
    default : whatToBring = 'Play it by ear';
}

OO way to do the construct

var whatToBring = {
    'Sunny' : 'Sunscreen and hat',
    'Rain' : 'Umbrella and boots',
    'Cold' : 'Scarf and Gloves',
    'Default' : 'Play it by ear'
}

var gear = whatToBring[weather] || whatToBring['Default'];
try Statement

The try class of statements should have the following form:

try {
    statements
} catch (variable) {
    statements
}

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

Avoid use of the continue statement. It tends to obscure the control flow of the function.

with Statement

Why it shouldn’t be used.

Why it should be used.

with statement Both points are valid. Understand how it works before you use it. It aint going to work with strict mode anyway, for good reason IMHO.

Function Declarations

  • All functions should be declared before they are used.
  • Inner functions should follow the var statement. This helps make it clear what variables are included in its scope.
  • There should be no space between the name of a function and the ( (left parenthesis) of its parameter list.
  • There should be one space between the ) (right parenthesis) and the { (left curly brace) that begins the statement body.
    The body itself is indented four spaces.
    The } (right curly brace) is aligned with the line containing the beginning of the declaration of the function.

This convention works well with JavaScript because in JavaScript, functions and object literals can be placed anywhere that an expression is allowed.
It provides the best readability with inline functions and complex structures.

function getElementsByClassName(className) {
    var results = [];
    walkTheDOM(document.body, function (node) {
        var a; // array of class names
        var c = node.className; // the node's classname
        var i; // loop counter

// If the node has a class name, then split it into a list of simple names.
// If any of them match the requested name, then append the node to the set of results.

        if (c) {
            a = c.split(' ');
            for (i = 0; i < a.length; i += 1) {
                if (ai === className) {
                    results.push(node);
                    break;
                }
            }
        }
    });
    return results;
}

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

div.onclick = function (e) {
   return false;
};

that = {
    method: function () {
         return this.datum;
    },
    datum: 0
};

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.

var collection = (function () {
    var keys = [], values = [];

    return {
    get: function (key) {
        var at = keys.indexOf(key);
        if (at >= 0) {
             return values[at];
        }
    },
    set: function (key, value) {
        var at = keys.indexOf(key);
        if (at < 0) {
            at = keys.length;
        }
        keysat = key;
        valuesat = value;
    },
    remove: function (key) {
        var at = keys.indexOf(key);
        if (at >= 0) {
            keys.splice(at, 1);
            values.splice(at, 1); }
        }
    };
}());

Variable Declarations

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 become implied globals.
If you get into the habit of using strict mode, you’ll get pulled up on this anyway.
Implied global variables should never be used.

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

It is preferred that each variable be given its own line. They should be listed in alphabetical order.

var currentSelectedTableEntry;
var indentationlevel;
var sizeOfTable;

JavaScript does not have block scope (see Scope section), so defining variables in blocks can confuse programmers who are experienced with other C family languages.

  • Define all variables at the top of the function.
  • Use of global variables should be minimized.
  • Implied global variables should never be used.

References

http://javascript.crockford.com/code.html

http://www.webreference.com/programming/javascript/prototypal_inheritance/

http://javascript.crockford.com/prototypal.html

http://www.crockford.com/javascript/inheritance.html

http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Moving to TDD

December 1, 2012

My last employers software development team recently took up the challenge of writing their tests before writing the functionality for which the test was written. In software development, this is known as Test Driven Development or TDD.

TDD is a hard concept to get developers to embrace. It’s often as much of a paradigm shift as persuading a procedural programmer to start creating Object Oriented designs. Some never get it. Fortunately we had a very talented bunch of developers, and they’ve taken to it like fish to water.

The first thing to clear up is that TDD is not primarily about testing, but rather it forces the developer to write code that is testable (the fact the code has tests written for it and running regularly is a side effect, albeit a very positive one).

This is why there is often some confusion about TDD and the fact it or its derivatives (BDD, ATDD, AAT, etc.) are primarily focused on creating well designed software. Code that is testable must be modular, which provides good separation of concerns.

  • Testing is about measuring where the quality is currently at.
  • TDD and its derivatives are about building the quality in from the start.

red green refactor

TDD concentrates on writing a unit test for the routine we are about to create before it’s created. A developer writes code that acts as a low-level specification (the test) that will be run on the routine, to confirm that the routine does what we expect it will do.

To unit test a routine, we must be able to break out the routines dependencies and separate them. If we don’t do this, the hierarchy of calls often grows exponentially.

Thus:

  1. We end up testing far more than we want or need to.
  2. The complexity gets out of hand.
  3. The test takes longer to execute than it needs to.
  4. Thus, the tests don’t get run as often as they should because we developers have to wait, and we live in an instant society.

This allows us to ignore how the dependencies behave and concentrate on a single routine. There are a number of concepts we can instantiate to help with this.

We can use:

Although TDD isn’t primarily about testing, its sole purpose is to create solid, well designed, extensible and scalable software. TDD encourages and in some cases forces us down the path of the SOLID principles, because to test each routine, each routine must be able to stand on its own.

SOLID principles

So what does SOLID give us? SOLID stands for:

  • Single Responsibility Principle
  • Open Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

Single Responsibility Principle

  • Each class should have one and only one reason to change.
  • Each class should do one thing and do it well.

Single Responsibility Principle

Just because you can, doesn’t mean you should.

Open Closed Principle

  • A class’s behaviour should be able to be extended without modifying it.
  • There are several ways to achieve this. Some of which are polymorphism via inheritance, aggregation, wrapping.

Liskov Substitution Principle

Interface Segregation Principle

  • When an interface consists of too many members, it should be split into smaller and more specific (to the client’s needs) interfaces, so that clients using the interface only use the members applicable to them.
  • A client should not have to know about all the extra interface members they don’t use.
  • This encourages systems to be decoupled and thus more easily re-factored, extended and scaled.

Dependency Inversion Principle

  • Often implemented in the form of the Dependency Injection Pattern via the more specific Inversion of Control Principle (IoC). In some circles, known as the Hollywood Principle… Don’t call us, we’ll call you.

TDD assists in the monitoring of technical debt and streamlines the path to quality design.

Additional info on optimizing your team’s testing effort can be found here.