How to structure MY JavaScript

I’ve seen loads of posts and confusion and questions and answeres about how to structure client side JavaScript in a maintainable way and my conclusion is there is no right way. Whether right or wrong for your projects, this is how I do it.

There are a some rules that I want my JavaScript to abide by.

1. Avoid multiple JavaScript files.

There is an argument to be had here, why would you include all code on every action (or page)? I just find it simpler, reference one file called app.js and be done with it then invoke the code that is relevant to the current action. Additionally this means one (granted larger) request to the server instead of one for common JavaScript and one for page specific JavaScript and even more for each of libraries you use.

2. Don’t write code that sits in the global scope

This can have unintended consequences such as overwriting functionality.

Taken from http://dev.opera.com/articles/view/javascript-best-practices/#avoidglobals:

Global variables and function names are an incredibly bad idea. The reason is that every JavaScript file included in the page runs in the same scope. If you have global variables or functions in your code, scripts included after yours that contain the same variable and function names will overwrite your variables/functions.

The issues is discussed at length at that link and countless other sources on the internet, so I won’t talk about the problem, just the solution. I like to use closures, sometimes called Immediately Invoked Function Expressions to solve this issue.

The simplest possible closure is:

(function () {
    // Properly scoped code here.
})();

You can read more about JavaScript closures and IIFE’s here.

3. Use namespacing in your JavaScript files
In my single app.js file, I like to implement a series of closures representing different namespaces. This is typically the term app followed by a namespace for each action. This improves readability and helps my brain action page logically.

var app = (function () {
    // App specific code.
})();

var app.index = (function () {
    // Index specific code.
})();

var app.about = (function () {
    // About specific code.
})();

4. Implement an ‘init’ method in each closure.

Quite often there will be some start up code that needs to run, wiring up events or setting default values for example. This should be done in the init method. I like to implement a base class type hierarchy using this method too.

Take the code below as an example:

var app = (function () {
    function init() {
        // App specific code.
    }

    return {
        init: init,
    };
})();

app.index = (function () {
    function init() {
        app.init(); // Calls the code required for each page.
    }

    return {
        init: init,
    };
})();

The code required to initialise run this JavaScript is very minimal and simple.

<script src="~/Assets/js/app.js"></script>
<script>
    app.index.init();
</script>

5. Follow and stick to a certain code style.

  • I use single quotes (‘) instead of double quotes (“) so
    type: 'POST'

    instead of

    type: "POST"

    .

  • Spaces or tabs for indentations, I like to use four spaces, never two and never tabs.

Do the above points really matter? Probably not in the grand scheme of things, to code works as intended, but a I crave consistency my applications, it helps me work better and more importantly quicker if lines are laid out as I would expect.

So what do you guys think? I’m not saying this is the right or best way to do this – sometimes exceptions are required such as multiple namespace levels in larger projects.

I want to again point out that this is just MY way to do this and so far it has worked very well. Please post in the comments anything you do differently in your projects.

About these ads
Tagged ,

2 thoughts on “How to structure MY JavaScript

  1. slart2012 says:

    I studied under a guy who insisted that anything that could be sourced from a database should be sourced from a database. He favoured postgresql and would store 90% of any web app on the database and would use php with regular expressions to make a naming systems and to query the data from the database.

    Like you said in your article its not that this is the best standard and I certainly do not like using the database so much but it is feasible to effectively store JS in a database to be queried as required. Just an alternative I’ve done this and as you’ve documented one script file but being a student I can afford to be a dirty programmer with script not well documented scattered all over the place I have to admit this is usually my favoured method.

    • Anthony says:

      As a technical exercise, I can see some benefit, teaching regex in a practical example. In practice the approach described would be a nightmare to scale not to mention the nightmare of maintaining the expressions.

      The wheel has been reinvented, there are few use cases where this would be an elegant solution but school doesn’t always teach you the right way, rather interesting concepts in clever ways.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: