Organizing your JavaScript code Better

JavaScript is an interesting language because it is flexible and surprisingly powerful. Once you grow up from having one static page into having a large number of pages in a dynamic web application, you need conventions on how to organize your code.

In my opinion, there are two parts to the problem:
- The easy part, which is to apply JS programming patterns
- The hard part, which is doing so in a consistent and maintainable manner

Please go to the full post page for details.


Sampled by © JavaScriptBank.com

Javascript is an interesting language because it is flexible and surprisingly powerful. Once you grow up from having one static page into having a large number of pages in a dynamic web application, you need conventions on how to organize your code.

In my opinion, there are two parts to the problem:

  1. the easy part, which is to apply JS programming patterns
  2. the hard part, which is doing so in a consistent and maintainable manner

The easy part: Namespaces, modules and commenting conventions

Namespace and module pattern

Javascript has no explicit syntax for advanced language features such as namespaces and private variables, but these can be implemented using very simple programming patterns.

A lot has been written on the namespace and module pattern, so I will only illustrate it here.

I like to add a "placeholder" function shown below to prevent me from making errors while modifying the module (IE6 freaks out if there is a comma after the last item). This used to happen when I moved or added the methods and forgot to check whether that the commas are correct.

The example code below is adopted from (http://yuiblog.com/blog/2007/06/12/module-pattern/):

// create a namespace
YAHOO.namespace("myProject");
// Assign the return value of an anonymous function to the namespace

/** @namespace */
YAHOO.myProject.myModule = function () {
	/** @private */

	var myPrivateVar = "I can be accessed only from within YAHOO.myProject.myModule.";
 
	/** @private */
	var myPrivateMethod = function () {

		YAHOO.log("I can be accessed only from within YAHOO.myProject.myModule");
	}
 
        /** @scope YAHOO.myProject.myModule */
	return  {

		/** describe myPublicProperty here */
		myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty."
		/** describe myPublicMethod here */
		myPublicMethod: function () {

			YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");
 
			//Within myProject, I can access "private" vars and methods:
			YAHOO.log(myPrivateVar);

			YAHOO.log(myPrivateMethod());
 
			//The native scope of myPublicMethod is myProject; we can
			//access public members using "this":

			YAHOO.log(this.myPublicProperty);
		},
		/**
		* A placeholder function to prevent errors due to not having a comma after the last function in the return statement for this module.
		*/

		placeholder: function () {}
};
 
}(); // the parens here cause the anonymous function to execute and return

Commenting conventions. Pick a commenting tool and stick with it. Comment the intent of the code and any gotchas as well as the expected arguments and purpose of methods.

The two main JavaScript commenting tools are: JsDoc-Toolkit (self-contained Java) and YuiDoc (Python).

File names and splitting code into files. Put all the hard-to-reuse code into its own namespace (ex. Framework. ModuleName. ModulePart.ApplicationName) in a separate file (application.js or custom.js). This way you keep the library clean of any application-specific stuff. It is often hard to avoid implementing some things in a one-off manner, so you might as well organize all the single-use stuff in its own file.

That is, if writing your own extensions to an existing framework, you will most likely have:

  1. code that is fully reusable (specialized or pre-configured widgets, utilities etc.)
  2. code that is hard or pointless to reuse (page- or application-specific messages, formatting and utilities)

The hard part: structuring code for reuse, logical naming conventions

Structuring code for reuse. Encourage reuse by splitting code into configuration, implementation and customization.

  1. Configuration is anything that might need to change on each instantiation of your widget. It should be single section within a module (a private object in JSON notation). Make sure you have good and documented defaults, because this makes it easier to use the code again.
  2. Implementation is the main code. It should NEVER contain hardcoded ID's, messages or other things that will eventually need to be overridden.
  3. Customization is a set of page-specific blocks of code that alter the configuration. You only override the few things that are needed for the specific functionality on the page.

Here is an example (from http://www.wait-till-i.com/2008/05/23/script-configuration/):

myProject.myModule = function(){

// CONFIGURATION
  var config = {
    CSS:{
     classes:{

       hover:'hover',
       active:'current',
       jsEnabled:'js'

     },
     ids:{
       container:'maincontainer'
     }

    },
    timeout:2000,
    userID:'chrisheilmann'
  };

 
  // IMPLEMENTATION
  function init(){ };
  // make init and config public

  return {
    init:init,
    config:config
  };

}();
 
// CUSTOMIZATION
// This makes it possible to override stuff before calling init
module.config.CSS.ids.container = 'header';

module.config.userID = 'alanwhite';
module.init();

Naming conventions. I don't mean deciding whether or not to use camelCase, but rather how the logical organization names of variables and widgets should be done. It is reasonably simple to stop using global variables and functions to avoid name conflicts, but what is harder is to come up with a logical naming convention that allows any code to be reused anywhere.

In particular, when you create new widgets, you often need to be able to connect them to one another in some manner. Being able to identifying the type (class) and retrieve/replace data from a new widget using a standard interface takes some planning and a lot of discipline, but it makes reusing the widgets much easier.

ID and name attribute naming convention. I use "data[widgetName][recordIndex][fieldName]" for input names (because PHP will parse this into arrays automatically) and "widgetName_fieldName_recordIndex" for ID attributes (because it makes string comparisons easier).

Widget instance naming convention. I use YAHOO.ApplicationName.WidgetInstanceName for widget instances, and use WidgetInstanceName to create any related tags with IDs.

I am still looking for a good logical naming convention for widgets, but it seems this topic is not as commonly discussed. If you have any tips, please leave a comment!

Reference stuff

http://stackoverflow.com/questions/211795/are-there-any-coding-standards-for-javascript

http://ajaxian.com/archives/maintainable-javascript-videos-are-now-available

http://yuiblog.com/blog/2007/06/12/module-pattern/

http://www.wait-till-i.com/2008/05/23/script-configuration/

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
Insights for Advanced Zooming and Panning in JavaScript Charts
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website


Top view articles
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
Top 10 Beautiful Christmas Countdown Timers
Top 10 Best JavaScript eBooks that Beginners should Learn
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com