Skip to content

Javascript coding standards

zenmiu edited this page Aug 11, 2011 · 4 revisions

1. Introduction

The requirements below apply to JavaScript code used in the LiteCommerce software, except third-party JavaScript libraries included in the distribution kit “as is”.

2. Base standard

Not available.

3. JavaScript code requirements

3.1 Forming names

3.1.1 General requirements

Required:

Class names, function names and significant variable names should always be self-explanatory, so that a reader could immediately understand what they are used for.

3.1.2 Abbreviations

Required:

Naming format - Upper case.

Example:

function getHTMLStatistic  // correct
function getHtmlStatistic  // incorrect

3.1.3 Class names

In JavaScript, there are no classes as such. The term implies functions that are used for creating new objects.

Required:

  • Naming format - Pascal Casing.
  • Each new word begins with a capital letter; the remainder of the word — lowercase letters, except abbreviations.

Example:

function Product() {
}
Product.prototype.getPrice = function() {
}
var product = new Product();

Recommendations:

  1. Name a class only when you know what the class will do, how it will do that, and what for. If you do not know that, it is quite possible that you have not fully thought through the concept of the module.
  2. Do not be tempted to name a child class after its parent class. It is better that the class lives its own life, regardless of its parent.

3.1.4 Method names

Required:

Naming format - Camel Casing.

A method or function usually performs a certain action; therefore, its name must give a clear idea of the action it is made to perform. The difference between a method/function name and a property/variable name is that a method does something, while a property is or stores something.

function uniqueId()      // bad
function getUniqueId()   // good

function string()        // bad
function isString()      // good

function value()         // bad
function setValue()      // good

Recommended suffixes:

  • Max - to indicate the maximum value.
  • Count - to indicate the current value of a certain counter.
  • Key - to indicate the key value. Example: RetryMax contains the maximum number of available attempts, and RetryCount - current attempt number.

Recommended prefixes:

  • is - to indicate a question. Wherever you see is, you always know that this is a question.
  • get - to indicate getting a value.
  • set - to indicate setting a value.

Example:

isHitRetryLimit() [Something like: Is this the last attempt?]

Example:

Name_One_Two.prototype.doIt() = function() {};
Name_One_Two.prototype.handleError = function() {};

3.1.5 Variable names

Required:

Naming format - Camel Casing. First word - noun.

Example:

var errorCode
var productId

3.1.6 Class variable names

Required:

Same as in 3.1.5.

Example:

Product.prototype.errorCode
Product.prototype.productId

3.1.7 Method / function argument names

Required:

Same as in 3.1.5.

Example:

function getProduct(errorCode, productId) { }

3.1.8 Array key names

Required:

Array keys are named according to the variable naming rules (see 3.1.5).

Example:

myarr['fooBar'] = 'Hello';

3.1.9 Internal constant objects true, false, null

Required:

Boolean and numeric literals – true, false and null – are typed in the lower case. [REQ.JS.3.1.9]

3.1.10 Files

Required:

  • Naming format - Pascal Casing.
  • Always use the .js extension.

3.2 JavaScript code

Required:

Place as much of JavaScript outside the HTML files as possible, as JavaScript considerably increases the size of the page, which is dynamic and not cached.

3.3 <script /> tag

Required:

It is recommended to format the <script> tag according to the following example:

<script src="filename.js" type="text/javascript"> </script>

<script type="text/javascript">
<!--
...
-->
</script>

3.4 Appearance

Required:

  • Use 4 spaces for indenting inside separate .js files.
  • Use 2 spaces for indenting within individual <script> tags.

3.5 Line length

Recommended:

It is not recommended to make lines of JavaScript code longer than 80 characters.

3.6 Comments

Recommended:

It is recommended to comment non-trivial chunks of code. That information will be helpful to people (maybe you) who will work with the code later on. Comments must be clear and complete.

3.7 Variable declarations

Required:

  • All variables are to be declared before the use.

  • A value must be explicitly assigned to all variables when declaring. [REQ.JS.3.7]

  • Each variable is to be defined on a new line. [REQ.JS.3.7]

  • The var keyword is to be specified at the very beginning of the function body, except variables used as loop counters. Those can be declared directly in the loop:

    var x; // bad var y = false; // good

    for (var i = 0; i < len; i++) { }

Recommended:

It is recommended to comment variable definitions.

var currentEntry = false; // currently selected table entry
var level = false;        // indentation level
var size = false;         // size of table

3.8 Global variables

Required:

Using global variables (window object’s variables used for other objects’ purposes) is not allowed.

3.9 Function declarations

Required:

  • No blanks go between function name and the ( (left round bracket) of the argument list. [REQ.JS.3.9]
  • One space is inserted between the ) (right round bracket) and the { (left curly bracket) that opens the function body. [REQ.JS.3.9]
  • Function body must be indented to the next level.
  • } (right curly bracket) must appear precisely underneath the beginning of the function declaration.
  • If a function is declared anonymously (without a name), separate the function keyword and the opening round bracket with a space. [REQ.JS.3.9]

Example:

function outer(c, d) {
   var e = c * d;

   function inner(a, b) {
       return (e * a) + b;
   }

   return inner(0, 1);
}

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

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

   datum: 0
};

3.10 Expressions

3.10.1 Simple expressions

Required:

  • Terminate each expression with ; (semicolon).
  • Each line may contain one expression.

3.10.2 Compound expressions

Compound expressions are those that contain lists of other expressions enclosed in curly brackets.

Required:

  • Internal expressions are to be written with the next indentation level.
  • The opening curly bracket is to be aligned to the beginning of the compound expression.
  • The closing curly bracket is to be placed on a new line and aligned to the beginning of the compound expression.
  • The brackets are to frame any expression if it is a part of a control structure, such as if or for expression.

3.10.3 Labels and with

Required:

  • Labels are not allowed.[REQ.JS.3.10.3]
  • Using with is not allowed.[REQ.JS.3.10.3]

3.10.4 return expression

Required:

The _return_ expression may not have brackets around the return value. [REQ.JS.3.10.4]
The _return_ expression must be preceded by a blank line. [REQ.JS.3.10.4]

3.11 Control structures

Required:

  • In control structures, there must be a space between the key word and the opening bracket.
  • The opening bracket is to be placed on the same line with the respective operator.
  • The closing bracket is to be placed on the same indent with the operator.
  • The closing curly bracket is to be placed on the next (following the conventional code) line.
  • The entire content between the brackets is to be indented.
  • The code in the body is always framed by curly brackets.
  • Values cannot be assigned to variables within control structures, except within for.

Extension of requirements for operator if/else/else if:

Required:

  • The else if combination is placed on a single line.
  • A block of code within curly brackets is to be followed by a blank line.
  • If a block of code within curly brackets is large, it is recommended to leave one blank line before that block, following the if/else/else if.

Extension of requirements for operator switch:

Required:

  • The case block, passing the control further down, must have a comment.
  • The default block is always present.
  • Each case block must be followed by a blank line, separating the block from the neighbor.
  • The content of each case expression must be additionally indented.

Extension of requirements for ternary conditional operator <condition> ? <variant1> : <variant2>:

Recommended:

  • Enclose the condition expression in brackets, thus distinguishing it from the rest of the code.
  • Where possible, the actions to be performed on the condition should be simple functions.
  • If the entire branch block, located on a single line, is difficult to read, place the variant1 and variant2 blocks on a separate line each.

Extension of requirements for operator for:

Required:

The for ( element in array) construction is not allowed, except in the iterator functions included in the core.

Example:

if ((condition1) || (condition2)) {
   action1;

} else if ((condition3) && (condition4)) {
   action2;

} else {
   defaultaction;
}

switch (...) {
   case 1:
       ...
       // break intentionally omitted

   case 2: {
       v = getWeekNumber();
       ...
       }
       break;

   default:
       ...
}

(condition) ? func1() : func2();

or

(condition)
   ? long statement
   : another long statement;

Recommended:

Minimize the use of continue and break.

3.12 Blank lines

Required:

Inserting blank lines improves the readability of the code, separating logically bound chunks of code from one another.

Spaces are used in the following cases:

  • A keyword and an opening round bracket following it must be separated with a space:

      while (true) {
    
  • All binary operators, except the decimal point ".", opening round bracket "(" and opening square bracket "[" are to be separated from the respective operands with spaces.

  • Spaces should not be used when separating unary operators from their operands, except typeof.

  • Each semicolon ";" in the for operator must be followed by a space.

  • A space must follow each comma ",".

3.13 Additional recommendations

3.13.1 {} and []

Required:

  • Use {} instead of new Object(). [REQ.JS.3.13.1]
  • Use [] instead of new Array(). [REQ.JS.3.13.1]

3.13.2 Comma operator

Recommended:

Whenever possible, avoid using this operator.

3.13.3 Operators === and !==

Recommended:

It is recommended to use operators === and !== instead of == and != respectively. [WRN.JS.3.13.3]

3.13.4 Unclear pluses and minuses

Required:

Using + for indicating the sign of the figure is not allowed.

Example:

total = subtotal + +myInput.value;   // bad

total = subtotal + (+myInput.value); // bad

total = subtotal
tmp = parseFloat(myInput.value);
if (!isNaN(tmp))
 total += tmp;

3.13.5 eval and new Function

Required:

  • Do not use the eval function or its aliases. [REQ.JS.3.13.5]
  • Do not use the Function constructor. [REQ.JS.3.13.5]

3.13.6 setTimeout and setInterval

Required:

Do not write string variables to functions setTimeout and setInterval.

setTimeout('alert(1)', 500);               // bad
setTimeout(function() { alert(1); }, 500); // good

3.13.7 Unary operators (++ / --)

Required:

Unary operators must be called on a separate line of code.

foo[i++] = j; // incorrect

foo[--j] = i; // incorrect

$foo[i] = j;
i++;            // correct

j--;
foo[j] = i;   // correct

3.13.8 _defineGetter_ and _defineSetter_

Required:

Using _defineGetter_ , _defineSetter_ and similar constructions is not allowed, as they are not standard and obsolete.

See more information about these properties of the Object prototype.

Clone this wiki locally