Commonly accepted best practices around code organization in JavaScript [closed]

Commonly accepted best practices around code organization in JavaScript [closed]

As JavaScript frameworks like jQuery make client side web applications richer and more functional, I’ve started to notice one problem…
How in the world do you keep this organized?

Put all your handlers in one spot and write functions for all the events?
Create function/classes to wrap all your functionality?
Write like crazy and just hope it works out for the best?
Give up and get a new career?

I mention jQuery, but it’s really any JavaScript code in general. I’m finding that as lines upon lines begin to pile up, it gets harder to manage the script files or find what you are looking for. Quite possibly the biggest propblems I’ve found is there are so many ways to do the same thing, it’s hard to know which one is the current commonly accepted best practice.
Are there any general recommendations on the best way to keep your .js files as nice and neat as the rest of your application? Or is this just a matter of IDE? Is there a better option out there?

This question was intended to be more about code organization and not file organization. There has been some really good examples of merging files or splitting content around.
My question is: what is the current commonly accepted best practice way to organize your actual code? What is your way, or even a recommended way to interact with page elements and create reuseable code that doesn’t conflict with each other?
Some people have listed namespaces which is a good idea. What are some other ways, more specifically dealing with elements on the page and keeping the code organized and neat?


Solution 1:

It would be a lot nicer if javascript had namespaces built in, but I find that organizing things like Dustin Diaz describes here helps me a lot.

var DED = (function() {

    var private_var;

    function private_method()
        // do stuff here

    return {
        method_1 : function()
                // do stuff here
        method_2 : function()
                // do stuff here

I put different “namespaces” and sometimes individual classes in separate files. Usually I start with one file and as a class or namespace gets big enough to warrant it, I separate it out into its own file. Using a tool to combine all you files for production is an excellent idea as well.

Solution 2:

I try to avoid including any javascript with the HTML. All the code is encapsulated into classes and each class is in its own file. For development, I have separate <script> tags to include each js file, but they get merged into a single larger package for production to reduce the overhead of the HTTP requests.

Typically, I’ll have a single ‘main’ js file for each application. So, if I was writing a “survey” application, i would have a js file called “survey.js”. This would contain the entry point into the jQuery code. I create jQuery references during instantiation and then pass them into my objects as parameters. This means that the javascript classes are ‘pure’ and don’t contain any references to CSS ids or classnames.

// file: survey.js
$(document).ready(function() {
  var jS = $('#surveycontainer');
  var jB = $('#dimscreencontainer');
  var d = new DimScreen({container: jB});
  var s = new Survey({container: jS, DimScreen: d});;

I also find naming convention to be important for readability. For example: I prepend ‘j’ to all jQuery instances.

In the above example, there is a class called DimScreen. (Assume this dims the screen and pops up an alert box.) It needs a div element that it can enlarge to cover the screen, and then add an alert box, so I pass in a jQuery object. jQuery has a plug-in concept, but it seemed limiting (e.g. instances are not persistent and cannot be accessed) with no real upside. So the DimScreen class would be a standard javascript class that just happens to use jQuery.

// file: dimscreen.js
function DimScreen(opts) { 
   this.jB = opts.container;
   // ...
}; // need the semi-colon for minimizing!

DimScreen.prototype.draw = function(msg) {
  var me = this;

I’ve built some fairly complex appliations using this approach.

Solution 3:

You can break up your scripts into separate files for development, then create a “release” version where you cram them all together and run YUI Compressor or something similar on it.

Solution 4:

Inspired by earlier posts I made a copy of Rakefile and vendor directories distributed with WysiHat (a RTE mentioned by changelog) and made a few modifications to include code-checking with JSLint and minification with YUI Compressor.

The idea is to use Sprockets (from WysiHat) to merge multiple JavaScripts into one file, check syntax of the merged file with JSLint and minify it with YUI Compressor before distribution.


  • Java Runtime
  • ruby and rake gem
  • You should know how to put a JAR into Classpath

Now do

  1. Download Rhino and put the JAR (“js.jar”) to your classpath
  2. Download YUI Compressor and put the JAR (build/yuicompressor-xyz.jar) to your classpath
  3. Download WysiHat and copy “vendor” directory to the root of your JavaScript project
  4. Download JSLint for Rhino and put it inside the “vendor” directory

Now create a file named “Rakefile” in the root directory of the JavaScript project and add the following content to it:

require 'rake'

ROOT            = File.expand_path(File.dirname(__FILE__))
OUTPUT_MERGED   = "final.js"
OUTPUT_MINIFIED = "final.min.js"

task :default => :check

desc "Merges the JavaScript sources."
task :merge do
  require File.join(ROOT, "vendor", "sprockets")

  environment  =".")
  preprocessor =

  %w(main.js).each do |filename|
    pathname = environment.find(filename)

  output = preprocessor.output_file, OUTPUT_MERGED), 'w') { |f| f.write(output) }

desc "Check the JavaScript source with JSLint."
task :check => [:merge] do
  jslint_path = File.join(ROOT, "vendor", "jslint.js")

  sh 'java', '',
    jslint_path, OUTPUT_MERGED

desc "Minifies the JavaScript source."
task :minify => [:merge] do
  sh 'java', '', '-v',

If you done everything correctly, you should be able to use the following commands in your console:

  • rake merge — to merge different JavaScript files into one
  • rake check — to check the syntax of your code (this is the default task, so you can simply type rake)
  • rake minify — to prepare minified version of your JS code

On source merging

Using Sprockets, the JavaScript pre-processor you can include (or require) other JavaScript files. Use the following syntax to include other scripts from the initial file (named “main.js”, but you can change that in the Rakefile):

(function() {
//= require "subdir/jsfile.js"
//= require "anotherfile.js"

    // some code that depends on included files
    // note that all included files can be in the same private scope

And then…

Take a look at Rakefile provided with WysiHat to set the automated unit testing up. Nice stuff 🙂

And now for the answer

This does not answer the original question very well. I know and I’m sorry about that, but I’ve posted it here because I hope it may be useful to someone else to organize their mess.

My approach to the problem is to do as much object-oriented modelling I can and separate implementations into different files. Then the handlers should be as short as possible. The example with List singleton is also nice one.

And namespaces… well they can be imitated by deeper object structure.

if (typeof org === 'undefined') {
    var org = {};

if (!org.hasOwnProperty('example')) {
    org.example = {};

org.example.AnotherObject = function () {
    // constructor body

I’m not big fan of imitations, but this can be helpful if you have many objects that you would like to move out of the global scope.

Solution 5:

The code organization requires adoption of conventions and documentation standards:
1. Namespace code for a physical file;

Exc = {};

2. Group classes in these namespaces javascript;
3. Set Prototypes or related functions or classes for representing real-world objects;

Exc = {};
Exc.ui = {};
Exc.ui.maskedInput = function (mask) {
    this.mask = mask;
Exc.ui.domTips = function (dom, tips) {
    this.dom = gift; = tips;

4. Set conventions to improve the code. For example, group all of its internal functions or methods in its class attribute of an object type.

Exc.ui.domTips = function (dom, tips) {
    this.dom = gift; = tips;
    this.internal = {
        widthEstimates: function (tips) {
        formatTips: function () {

5. Make documentation of namespaces, classes, methods and variables. Where necessary also discuss some of the code (some FIs and Fors, they usually implement important logic of the code).

  * Namespace <i> Example </i> created to group other namespaces of the "Example".  
Exc = {};
  * Namespace <i> ui </i> created with the aim of grouping namespaces user interface.
Exc.ui = {};

  * Class <i> maskdInput </i> used to add an input HTML formatting capabilities and validation of data and information.
  * @ Param {String} mask - mask validation of input data.
Exc.ui.maskedInput = function (mask) {
    this.mask = mask;

  * Class <i> domTips </i> used to add an HTML element the ability to present tips and information about its function or rule input etc..
  * @ Param {String} id - id of the HTML element.
  * @ Param {String} tips - tips on the element that will appear when the mouse is over the element whose identifier is id <i> </i>.
  Exc.ui.domTips = function (id, tips) {
    this.domID = id; = tips;

These are just some tips, but that has greatly helped in organizing the code. Remember you must have discipline to succeed!

Solution 6:

Following good OO design principals and design patterns goes a long way to making your code easy to maintain and understand.
But one of the best things I’ve discovered recently are signals and slots aka publish/subscribe.
Have a look at
for a simple jQuery implementation.

The idea is well used in other languages for GUI development. When something significant happens somewhere in your code you publish a global synthetic event which other methods in other objects may subscribe to.
This gives excellent separation of objects.

I think Dojo (and Prototype?) have a built in version of this technique.

see also What are signals and slots?