Commonly accepted best practices around code organization in JavaScript

Hugoware picture Hugoware · Oct 29, 2008 · Viewed 49.8k times · Source

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?


EDIT

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?

Answer

polarbear picture polarbear · Oct 29, 2008

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.