Skip to content

JavaScript Programming Practices

Scott Shillcock edited this page Aug 27, 2010 · 1 revision

Introduction

About This Guide

This guide is divided into three sections. The first section, JavaScript Programming Style, covers the formatting style used when coding for the platform. The second section, JavaScript Programming Conventions, covers coding conventions specific to the JavaScript language. The third section, Platform Programming Conventions, covers coding practices specific to the platform.

Architectural Goals

The platform was created to provide a clean and modular code base for the development of interactive applications. The architecture was designed to minimize interdependencies and maximize code reuse. Performance must be balanced against design and reusability to ensure a clean and usable code base. The platform was designed to be very dynamic such that code that is not needed is not loaded. This dynamism is extended to the data used during runtime. Things like enumerations and data hierarchies are configured at runtime and not hardwired into the code.

Document Conventions

The following conventions are used in this document:

Italics Used for filenames, directory names, and URLs.

Constant Width

Used for code examples, system output, and command lines.

JavaScript Programming Style

Simple Source Code Formatting

To ensure that source code can be viewed on the widest range of text editors, a few simple guidelines are necessary.

Never use tabs for formatting. The amount of space a tab generates tends to vary from text editor to text editor and thus code that looks to be properly indented in one editor may look horribly mangled in another.

Each line of code should be no more than 90 characters wide. Not only does this improve readability, it also helps insure that formatting will be consistent regardless what text editor is used. The only exception to this rule is string literals which may span more than 90 characters.

Function Name Formatting

Function names should use camel case formatting. parenthesis formatting goes here

// Correctly named functions

var updateTimeSlice = function (time) { ... };
function updateChannelState(channel, state) { ... }

// Incorrectly named functions

var update_time_slice = function (time) { ... };
function UpdateChannelState (channel, state) { ... }

Variable Name Formatting

Variable names should use camel case formatting. Variable names should be chosen carefully. The name should describe how the variable will be used. Try and avoid single letter variable names especially letters like i and l as they can easily be confused for numbers. When defining variables in for loops, use the variable name count, or if the loop is nested, use two letter variable names like ix, jy, and kz.

Semicolon

var usage goes here

When the semicolon is used in a for loop, there should be no space between the semicolon and the argument it is terminating and a space between the semicolon and the start of the next argument.

// Correctly formatted semicolons in a for loop
for (ix = 0; ix < 10; ix++) {;}

// Incorrectly formatted semicolons in a for loop

for (ix = 0 ; ix < 10 ; ix++) {;}
for (jy = 0 ;jy < 10 ;jy++) {;}

Indentation

Standard indentation is three spaces. The code block should be indented within its enclosing curly brackets {}. Thus a code block enclosed in three sets of curly brackets should be indented nine spaces. Tab characters should never be used in formatting source code. Six-space indentation is used in function parameter lists and if/while/for expressions that require more than one line. The six spaces indentation rule is used to help visually separate expressions and function parameter lists from the code that follows.

// Correctly indented code

function aFunctionWithAReallyLongNameAndALotOfArguements(
      firstParam,
      secondParam,
      thirdParam,
      fourthParam) {

   var result
     , sum
     ;

   sum = firstParam + secondParam + thirdParam + fourthParam;

   if (sum > 100) {

      result = true;
   }
   else {

      result = false;
   }

   return result;
}

Curly Brackets

The opening curly bracket, {, should be on the same line as the expression that necessitates enclosing the code block in curly brackets. There must be a space between the opening curly bracket and the end of the expression. If the code block fits on one line, the closing curly bracket, }, can be on the same line as the opening curly bracket. There must be a space between the end of the code block and the closing curly bracket. If the code block is multiple lines long, the closing curly bracket should be on its own line and have the same amount of indentation as the expression that started the code block (e.g. if, while, for, etc.). There should be an additional carriage return between the opening curly bracket and the start of the indented code block.

// Correct use of curly brackets

if (foo != 0) { foo = 0; }
else {

   foo = getCount();
   foo = foo / maxCount;
}

do {

   self.log.out("Waiting");

   dmz.time.sleep (1);

} while (dmz.time.getFrameTime () < nextTime);

for (ix = 0; ix < maxCount; ix++) {

   if ((ix === realyLongVaribleName) &&
         (loopCount > 10) &&
         (smallCounter != 1)) {

      self.log.out("FOO!");
   }
}


// Incorrect use of curly brackets

if (foo != 0)
{
   foo = 0;
}
else
   {
   foo = getCount();
   foo = foo / maxCount;
   }

do
{  self.log.out("Waiting");
   dmz.time.sleep(1);}
while (dmz.time.getFrameTime() < nextTime);

for (ix = 0; ix < maxCount; ix++){
   if ((ix === realyLongVaribleName) &&
         (loopCount > 10) &&
         (smallCounter != 1))
   {

      self.log.out("FOO!");
}}

Square Brackets

Square brackets, [], should always have a space following the closing square bracket, ], unless it is followed by a semicolon, an opening square bracket, [, or a closing parenthesis, ), in which case there should be no trailing space.

// Correct square bracket formatting

var foo = intArray[10];

for ( /* ... */ ) {

   intArray[ix] = ix;
}

if (boolArray[ix]) {;}

if (obj["attrName"] === 123) {;}

// Incorrect square bracket formatting

var foo = intArray [10] ;


for ( /* ... */ ) {

   intArray[ ix ]= ix;
}

if (boolArray[ix] ) {;}

if (obj[ "attrName" ] === 123) {;}

Parenthesis (Round Brackets)

Parenthesis should have space on the convex side and no space the concave side. If more than one parenthesis of the same type is together, there should be no space between them. If a closing parenthesis, ), is followed by a semicolon, there should be no space between them

// Correct parenthesis formatting

if ((a == b) && (c == d)) {;}

while (!foo && (goo != 0)) {;}

var value = func (x, y, z);

// Incorrect parenthesis formatting

if( ( a == b )&&( c == d ) ){;}

while ( !foo && ( goo != 0 ) ) {;}

var value = func( x, y, z );

Operators

Unary operators (e.g. ++, --, !) should contain no space between themselves and the variable they are operating on and one space on the opposite side unless followed by a semicolon.

// Correctly formatted unary operators

foo = ++ix;

goo = -ix;

hoo = ix--;
    
var value = !otherValue;

// Incorrectly formatted unary operators

foo = ++ ix;

goo = - ix;

hoo = ix-- ;
    
var value = ! otherValue;

Operators (e.g. +, -, *, /, %, =, &&, ||, &, |, <, >, <=, >=, ===) should contain space on both sides.

// Correctly formatted operators

foo = goo + hoo;

goo = foo * hoo;

if (foo && goo) { hoo = foo - goo; }

// Incorrectly formatted operators

foo=goo+hoo;

goo= foo*hoo;

if (foo&&goo) { hoo =foo-goo; }

JavaScript Programming Conventions

Source File Layout

tbd

Function Results

Every function should contain at most one return. That return should be the last thing executed in the function. Multiple returns can cause confusion over function flow and can often introduce bugs when code is not executed due to a premature return. The returned value should always be name result.

Size of Function Body

Functions should never be overly large. If a function is over 60 lines in length, try and re-evaluate the function and determine if the function can be broken down into small parts. It is not always possible to keep functions short. If you have a function you feel is excessively long and are unsure how to proceed, consult with a senior software engineer.

Avoid Cut and Pasting Code

When coding, avoid cutting and pasting code from else where. If another portion of code contains functionality need in a piece of code being developed, break the common code out into a reusable class or function.

Loops: for vs. while

Use for loops when the number of iterations in the loop is known before the start of the loop execution or the loop is expect to complete regardless of the results of each iteration. Use while loops when the number of iterations is determined during the execution of the loop.

Things to Avoid

Never use break except in case statements. Breaking in a loop can cause confusion and problems much like multiple returns.

Never create a for loop with no arguments. (i.e. for (;;)). That sort of construct is just asking for an infinite loop.

More JavaScript avoids go here

Platform Programming Conventions

What is a Script? What is an Instance? What is a Module?

description goes here