10 Hot Tips for Refactoring Your Javascript

10 Hot Tips for Refactoring Your Javascript

This week I've had a departure from app development to build a web application for a new product we're developing at Airsource HQ. As with any web app this has involved a ton of Javascript, and along the way I picked up a few tips for refactoring that might be useful for your projects. 10 Hot one's as it happens...

  1. Use a script loader. This keeps your HTML clean (you just need to include one script) and allows you to set dependencies on loading scripts. I used requirejs for this and it was great!

  2. Namespaces. With Javascript the default for every variable declaration is global, so it's very easy to get in a mess when you want variables with names like 'user'.

    Declare a namespace like this:

    var MyNamespace = MyNamespace || {};
    

    Then from then onwards you can use:

    var MyNamespace.user = "Me";
    
  3. var i = 0. Without the keyword var, the variable is global. With it, the variable is valid only in the current scope (between the current set of curly braces). It's easy to forget to use it because it's not strictly required, but omitting it can lead to some weird and wonderful bugs. For example

    i = 0;
    while(i < 5)
    {
        console.log(i);
        i++;
    }
    // ... then later, even way later deep in a function...
    test();
    function test()
    {
        while(i < 5)
        {
            console.log(i);
            i++;
        }
    }
    

    You will get no error message for not declaring the second i, and the second loop won't run at all...

    See for yourself

  4. Modules are brilliant. Basically they are just a logical collection of functions and variables, analogous to static (or 'class') methods. You can encapsulate private data and functionality too. stevekwan has a really helpful example that I used.

  5. Classes - also brilliant. Unlike modules you are creating object instances - perfect for wrapping up data from the data model for example. I used another example from stevekwan that shows how to make methods and members public and private.

  6. Polymorphism - kind of. Because Javascript is very weakly typed, it's difficult to ensure that a class implements the right methods, but if you are careful you can use this weak typing to your advantage. For example, call a method on an object in a list regardless of what type the object is at runtime. Just remember to handle the error if the method does not exist.

  7. Use jQuery jQuery is a pretty big script to load, but for any largish web application it is brilliant. It provides a load of really useful wrappers for standard Javascript functions that you need to call all the time. For example each() provides a quick way of looping through elements:

    $(".li").each(function()
    {
        $(this).html("<p>It works!<p>")
    }
    

    With jQuery you can also easily create...

  8. Custom controls. It is very likely you will need re-usable custom controls throughout the application. I used this boilerplate to build a drop-zone plugin for dragging and dropping files for example.

  9. Wrap the console. The Javascript console is great for debugging, but it is limited to pretty basic logging, and you probably don't want any debug level logging when the app is deployed. There are plenty of open wrappers out there that add support for log levels etc, but it's pretty simple to wrap it yourself and you can even use the same module to display status in the UI for example.

  10. Embrace the script! If like me you are from a traditional OO background and don't like the word 'static', remember this is a scripting language, and that comes with benefits as well as drawbacks. Segmenting the codebase into logical chunks rather than pure objects can be very useful, readable and maintainable if done right.

These 10 tips are the key details I learnt working with JS for this project. I hope they help you refactor your JS and get a bit further up the never-ending software development learning curve.

James Uren
in Technical Tagged technical javascript web

Airsource design and develop apps for ourselves and for our clients. We help people like you to turn concepts into reality, taking ideas from initial design, development and ongoing maintenance and support.

Contact us today to find out how we can help you build and maintain your app.