Maintainable and Reusable JavaScript By Using Coding Conventions

It should be of no surprise that following conventions while programming can help foster maintainable and reusable code. This should be a simple concept to grasp since using agreed-upon rules up front for any form of communication will typically add clarity. Communication through programming is no different. So it makes sense that most programming languages use conventions to help clarify the meaning of the code. This is not only for your benefit, but also for the benefit of those who are going to be interpreting, reusing, and adding functionality to your Web site or Web application.

In this article, we are going to look at some JavaScript coding conventions. Of course, this is not the be-all and end-all list of JavaScript coding conventions. In fact, the specifics of each convention should be a secondary concern in comparison to having a convention at all, and actually being able to follow it. With that said, below are the conventions I find to be an essential complement to writing JavaScript.

Keep JavaScript External

This convention is rather broad as it pertains to Unobtrusive JavaScript techniques. In general, the idea is that JavaScript should be written and maintained in an external file (yes, this includes events too), separate from the (x)HTML pages, by using the script element with the accompanying “src” attribute, which then links the JavaScript file to the page.

CamelCase Naming

Similar to built-in JavaScript methods (e.g. – getElementById), identifiers should start with a lower case letter, and the first letter of each subsequent new word should be uppercase. The one exception to this rule is when defining a class. When defining a class, the identifier should start with an uppercase letter, and the first letter of each subsequent new word should be uppercase. Additionally, when creating identifiers it is a good idea to think of classes as nouns (e.g. – Rectangle) and methods/functions as verbs (e.g. – getRectangleSize).

/* - CamelCase */
	var my_variable_named_x; //NO
	var myvariablenamedx; //NO
	var myVariableNamesx; //YES

/* - An exception is that names start with a capital letter if it's a class (PascalCase) */
	function rectangleClass(w, h){ //NO
		this.width = w;
		this.height = h;
	function RectangleClass(w, h){ //YES
		this.width = w;
		this.height = h;

Avoid Underscores

Underscores should not be used in identifiers. However, private members of a class are often designated by starting the identifier with an underscore. Personally, I think this should be the only exception to the rule.

Use Spaces

I don’t think there is a hard and fast rule on this one. I have a personal preference, but instead of specifying how spaces should be used in each scenario, I suggest that space should be used after a comma or semicolon, and before and after the assignment (=) operator. Obviously, spaces must always be used with certain operators (e.g. – typeof, in, delete, void, new, instanceof). Remember that while JavaScript has some rules, it is considered a loosely typed language, and therefore, ignores tabs and white space. This is why it is possible to “minify” JavaScript code.

/* - using spaces after a comma, semicolon, and before and after the assignment (=) operator.*/
	var z=x; //NO
	var z,x,c; //NO
        var z = x; //YES
        var z, x, c; //YES

Use a Consistent Code Layout

Code layout is generally a matter of preference. However, if you have no preference, then I recommend you try the following for consistency’s sake:

/* - braces {} should be used on all statements, even with a 
single statement conditional. Notice the appropirate use of the 
semicolon for a single statement vs. a block statement.*/
	if(condition)statement; //NO
	if(condition){statement;} // YES
/* - each statement of a block statement should be on its own
line without the braces, and the contents of the statements 
should be indented unless you are using a single statment. */
	function functionName(parameters){//YES
/* - do not omit semicolons, nor allow the automated 
insertion of semicolons. The only time this should be allowed
is when a single statement is used instead of a block
statement */
	var x = 1 //NO
	var x = 1; //YES

	if(condition){ //NO
	if(condition){ //YES
/* - these are single (line) statements */
	var functionName = function(){statement} //NO
	var functionName = function(){statement;}; // YES
	function functionName(){statement} //NO
	function functionName(){statement;} // YES
	if(condition){statement} //NO
	if(condition){statement;} //Yes

Variables Should Use the “var” Keyword

All variables should be defined using the var keyword, especially inside of functions. More than anything, this helps to keep your variables in local scope as an instance of the function that contains it.

/* - variables should always be defined using var */
	i, i13, $i13; //NO
	var i, i13, $i13; //YES

	var myFunction = function(){i;} //NO
	var myFunction = function(){var i;} //YES

Use Parentheses To Show Order

Parentheses should be used to visually show the order in which operations are performed.

/* - Parentheses should always be used to show order */
	var myNumber = z+y*x; //No
	var myNumber = a?b:c?d:e; //No

	var myNumber = z+(y*x); //YES
	var myNumber = a?b:(c?d:e); //YES

Use Single Quotes For JavaScript

Use single quotes for JavaScript strings, and double quotes for (x)HTML.

/* - single quotes for JavaScript, and double for (x)html */
	var i = "<a href="link" title="&quot;+i+&quot;">"+z+"</a>"; //NO
	var i = '<a href="link" title="'+i+'">'+z+'</a>'; //YES

Use Unique Scopes

Programs should not be written so that variables are in the global scope of the document. Instead, variables that need to be accessed globally should be the key of a local method/property on an object literal, or a local method/property of a utility function.

/* - private scope using a function */
	var z = 0; //NO
	function myFunction(){
		var z = 0; //YES
		function myNestedFunction(){
			var z = 0; //YES

/* - using an anonymous function to create a private scope */
	var y = 0; //NO
	(function() { 
    	var y = 0; //YES

/* - using an anonymous function, called after an event to 
create a private scope */
	var w = 0; //NO
		var init = function(){
			var w = 0; //YES
		window.onload = function(){init();}

/* - unique scope using an object, also called
a namespace */
	var x = 0; //NO
	var myObject1 = {x:0}; //YES
	var myobject2 = {
		x:0, //YES
			x:0 //YES

Use Literals

Use literal expressions instead of the new operator.

/* - use literal expressions */
	var myNumber = new Number(432); //NO
	var myString = new String("This is a string"); //NO
	var myBoolean = new Boolean(true); //NO
	var myFunction = new Function("", "return this.location"); //NO
	var myRegExp = new RegExp("javascript"); //NO

	var myArray = new Array(); //NO
	myArray[0] = 1;
	myArray[1] = 2;
	myArray[2] = 3;
	myArray[3] = 4;
	myArray[4] = 5;

	var myBodyObject = new Object(); //NO
	myBodyObject.legs = 2;
	myBodyObject.arms = 2;
	myBodyObject.toes = 10;
	myBodyObject.fingers = 10;

	var myNumber = 432; //YES
	var myString = "This is a string"; //YES
	var myBoolean = true; //YES
	var myFunction = function (){return this.location;} //YES
	var myRegExp = /javascript/gi; //YES
	var myArray = [1,2,3,4,5]; //YES
	var myBodyObject = {legs:2, arms:2, toes:10, fingers:10}; //YES

Use Comments

Comments should be written either on the preceding line or to the right of the code in question. All of the previous code examples demonstrate this style of commenting.

Optimize Your Code

Minification and Obfuscation should be used where applicable. Here is another article about JavaScript Empty Array which will teach you how you can create an empty array or empty the content of an Array using most optimal technique.

Originally Written by

Write a Comment

Your email address will not be published. Required fields are marked *