javascriptscopeprivate-functions

Private functions in JavaScript


In a jQuery-based web application I have various script where multiple files might be included and I'm only using one of them at a time (I know not including all of them would be better, but I'm just responsible for the JS so that's not my decision). So I'm wrapping each file in an initModule() function which registers various events and does some initialization etc.

Now I'm curious if there are any differences between the following two ways of defining functions not cluttering the global namespace:

function initStuff(someArg) {
    var someVar = 123;
    var anotherVar = 456;

    var somePrivateFunc = function() {
        /* ... */
    }

    var anotherPrivateFunc = function() {
        /* ... */
    }

    /* do some stuff here */
}

and

function initStuff(someArg) {
    var someVar = 123;
    var anotherVar = 456;

    function somePrivateFunc() {
        /* ... */
    }

    function anotherPrivateFunc() {
        /* ... */
    }

    /* do some stuff here */
}

Solution

  • The major difference between these two approaches resides in the fact WHEN the function becomes available. In the first case the function becomes available after the declaration but in the second case it's available throughout the scope (it's called hoisting).

    function init(){
        typeof privateFunc == "undefined";
        var privateFunc = function(){}
        typeof privateFunc == "function";
    }
    
    function init(){
        typeof privateFunc == "function";
        function privateFunc(){}
        typeof privateFunc == "function";
    }
    

    other than that - they're basically the same.