Search code examples
javascriptperformancecoding-stylereadabilitymaintainability

Declaring variables and functions, in what order?


Context

I'm learning how to code in consistently, readably and maintainably.

I found nothing about the order of declaration of variables and functions.

Example:

var example = {

    A: function() {
        var a, b, c;
    },

    B: function() {
        var a, b, c;
    },

    C: function() {
        var a, b, c;
    }

}

Questions

  • Alphabetically is the best one ?
  • Is that the order can improve the speed of code execution ?

Solution

  • I use jslint to check the code quality. It can be integrated with Visual Studio and a lot of other stuff which is really nice.

    JSLint suggests using something like:

    var example = {
        A: function () {
            var a, b, c;
        },
    
        B: function () {
            var a, b, c;
        },
    
        C: function () {
            var a, b, c;
        }
    };
    

    Regarding the variables, it suggests declaring them always at the start of the enclosing scope, since that's actually how the code will be interpreted (that's the JavaScript semantic).

    Regarding performance, you cannot improve or decrease performance by changing the order.

    Regarding the order... You should do it in the order which has more sense to you (and your team). I personally like doing top-down or bottom-top (That means putting the most important functions first, and then put the dependent functions after that one, etc... or the other way around... Put the simpler functions first, and then the functions that build on top of those ones).