JavaScript Coding Standards

Introduction

 
This document provides the JavaScript coding standards for development. The goal is to define guidelines to enforce consistent style and formatting and help developers avoid common pitfalls and mistakes.
 
Code style is about consistency and discipline, and there's no real right or wrong. The first step would be to adhere to the style of the used platform and stick to that. It helps others reading your code, and helps you read the code of others in the same ecosystem, and can only be decided by personal preference. Guidelines posted here are not rules that you should comply to, but consider them as suggestions that can improve your code quality 
 

Naming Conventions

 
Consistency is the key to maintaining code. This statement is most true for naming your projects, source files, and identifiers including variables, properties, methods, parameters, classes, interfaces, and namespaces.
 
Identifier Type Rules for Naming Example
Namespaces Pascal Case; should start with the company namespace, followed by application "layers" as applicable Mcn.Contacts
Classes Nouns in Pascal Case class Mcn.Contacts.ManageContactsViewModel
Functions Verb or Verb/Noun pair in Camel Case initializeData ();
Constants All uppercase with words separated by underscores var MAX_CONTACTS_TO_DISPLAY = 200;
Instance Variable Camel Case var currentContacts = null;
Local Variable Camel Case var callBacks = {};
Parameters Camel Case function (contactSearchFilter)
 

Case sensitivity

 
To avoid confusion, follow these rules regarding the use of case sensitivity; do not create:
  • Two namespaces with names that differ only by case.
  • Functions with names that only differ by a single letter or number.
  • A type with method names that differ only by case.
  • Variables with a type that differs only by case.
  • Variables matching data type using a different case.

Coding Style

 
Consistent layout, format, and organization are keys to creating maintainable code. The following sections describe the preferred way to implement source code in order to create readable, clear, and consistent code that is easy to understand and maintain.
 

Formatting

  • Always use a namespace for a JavaScript file
  • Never declare more than 1 namespace per file
  • Avoid putting multiple "classes" in a single file
  • Always place curly braces ({ and }) on a new line
     
    Example
    1. var contactsAvailable = function ()  
    2. {  
    3. }; 
  • Always use curly braces ({ and }) in conditional statements.
     
    Example
    1. if (contactCount === 0)  
    2.     {  
    3.       // code for true case  
    4.     }  
    5.     else  
    6.     {  
    7.       // code for false case  
    8.     } 
  • Always put parenthesis around all clauses in if statements.
     
    Example
     
    Bad
    1. if (contactCount === 0 && retrievingData === true)  
    2. {  
    Good
    1. if ((contactCount === 0) &&  
    2. (retrievingData === true))  
    3. {  
  • Never make function calls within a clause of if statements.
     
    Example
     
    Bad
    1. if (getContacts().Count == 0)  
    2. {  
    Good
    1. var contactList = getContacts();  
    2. if (contactList.Count == 0)  
    3. {  
  • Do not use elseif to string if statements together.
  • Always use a Tab and Indention size of 2, inserted as spaces.
  • Declare each variable independently, not in the same statement.
     
    Example
     
    Bad
    1. var firstName, lastName; 
    Good
    1. var firstName  
    2. var lastName;  
  • Recursively indent all code blocks contained within braces. NOTE: Visual Studio supports formatting code by Edit/Advanced/Format Code (or control-K, control-D). This requires setting the Editor tabbing and spacing as indicated above.
  • Use white space (CR/LF, Tabs, and so on) liberally to separate and organize code.
  • If in doubt, always err on the side of clarity and consistency.
  • Parameters in method declarations should be on separate lines and all parameters should be left-aligned.
     
    Example
    1. var getPhoneNumber = function (contactData,phoneNumberIndex)  
    2. {  
    3. }; 
  • Parameters in method calls should be on separate lines with all parameters left-aligned.
     
    Example
    1. getPhoneNumber(contactData phoneNumberIndex);   
  • Do not insert spaces in a parameter list for method declarations or method calls NOTE: This behavior is configurable in Visual Studio.
     
    Example
    1. getPhoneNumber(contactDataphoneNumberIndex, dbConn, dbTrans); 
  • Declare all variables at the beginning of a function. Do not place declarations throughout the function body.

Commenting

  • All comments should be written in U.S. English.
  • Use // or /// but do NOT use /* */.
  • Commented out code should be code that will be soon deleted, and marked with a "TODO:".
  • Do not "flowerbox" comment blocks.
     
    Example
     
    Bad 
    1. // ********************************  
    2. //  Comment block  
    3. // ******************************** 
    Good
    1. // ********************************  
    2. //  Comment block   
  • Use inline-comments to explain assumptions, known issues, and algorithm insights.
  • Do not use inline-comments to explain obvious code. Well written code is self documenting.
  • Use "TODO:" task list tokens to mark incomplete methods or sections.
     
    Example
    1. // TODO: handle validation error 
  • Do NOT use "hack" or "undone" task list tokens. Other tokens may be added with team consensus and they are added to this document to define how they are to be used. 
  • Always apply comment-blocks (///) to classes. The class comment block should include the following.
     
    • Required 
       
      Description of the class and what it is used for 
       
    • Optional
       
      Remarks to provide further explanation of the class use. 
       
  • Always apply documentation comment blocks (///) to functions. Comment blocks should include the following sections.
     
    • Required
       
      Description to define what the function is used for.
       
    • Optional
       
      Remarks to convey more information about the method. This may include pseudocode for complicated methods.

Visual Studio .Net Environment Setup

  • Select Tools/Options
  • Select Text Editor
  • Select All Languages/Tabs and set the following:
     
    • Indenting: Block
    • Tab Size: 2
    • Tab Indent Size: 2
  • Select "Insert Spaces"
  • Select JavaScript/Formatting/General: check all checkboxes
  • Select JavaScript/Formatting/New Lines: check all checkboxes
  • Select JavaScript/Formatting/Spacing: check all checkboxes except "Insert space after opening and before closing non-empty parenthesis" that should be unchecked.

Language Usage

 

Variables and Types

  • All JavaScript code should be implemented in strict mode by placing "use strict" at the beginning of the "class", this helps in catching and preventing errors earlier in the development process.
  • All variables must be explicitly declared. Do not declare variable implicitly.
  • Declare all variables at the beginning of a function.
  • Avoid using inline numeric literals (magic numbers). Instead, use a constant or enum.
  • Avoid declaring inline string literals. Instead use Constants, Resources or other data sources.
  • Avoid concatenating strings inside a loop.
  • Do not compare strings to "" to check for empty strings. Use myString.length === 0.
  • Do not invoke methods in conditional statements.
  • Avoid creating recursive methods. Any perceived need for a recursive method must be reviewed by the team before implementation.

Comparisons

  • Always use === (3 equal signs) for comparison. This compares value and type and avoids implicit conversions for comparisons.
  • Always use !== for "not equal" comparisons. This compares value and type and avoids implicit conversions for comparisons.
  • Always compare a Boolean value to "true" or "false" for example if (pass === true). This ensures the variable is actually true and avoids issues associated with undefined values and Boolean comparisons.

Type Comparisons

 
Always use the following for type comparisons:
  • String: typeof variable === "string"
  • Number: typeof variable === "number"
  • Boolean: typeof variable === "boolean"
  • Object: typeof variable === "object"
  • Function: typeof variable === "function"
  • Undefined: variable === undefined
Hope that would help somebody. You can also download the guidelines, please find it attached.