Grow your CSS skills. Land your dream job.

Nesting functions: Good or Bad?

  • # December 31, 2013 at 3:39 am

    Please excuse my ignorance, but is there anything wrong with nesting multiple functions inside a parent function, which is then called to execute the contents inside? I’ve successfully tested the output, but wasn’t sure if it’s frowned upon.

    For example:

    function myFunc() {
    
        var = myVariable;
        var = anotherVariable;
    
        function one() {
    
            // Do Something
    
        }
    
        function two() {
    
            // Do Something Else
    
        }
    
        function three() {
    
            // Do Something Else
    
        }
    
    
    }
    
    // Call Function
    
    myFunc();
    
    # January 3, 2014 at 4:39 pm

    This is a matter of scope.

    With this set up it becomes much harder to call one(), two(), or three() outside the myFunc(). You can’t just use one() anywhere you want because you can only access it while inside myFunc().

    Try to keep functions separate. If a function needs to use another function inside it, just call it.

    function one() {
    
        // Do Something
    
    }
    
    function two() {
    
        // Do Something
    
    }
    
    function three() {
    
        // Do Something
    
    }
    
    function myFunc() {
    
        var = myVariable;
        var = anotherVariable;
    
        one() ;
    
        two();
    
        three();
    
    }
    
    // Call Function
    
    myFunc();
    

    If you need to use the variables set in myFunc() in one(), two(), and three() then just pass them into the function

    # January 3, 2014 at 6:54 pm

    On the other hand, this is exactly how you get private methods/variables in javascript.

    If your function is needed only inside the parent function, then declaring it inside the function means it won’t cause any problems with functions in other scope(s).

    function count(){ alert( "1, 2, 3, 4, 5" ); }
    
    function backwardsDay(){
        function count(){ alert( "5, 4, 3, 2, 1" ); }
    }
    

    The inner count method doesn’t conflict with the one in the global namespace, plus, the global namespace can’t use it: only backwardsDay can count backwards.

    # January 4, 2014 at 5:37 pm

    If your function is needed only inside the parent function, then declaring it inside the function means it won’t cause any problems with functions in other scope(s).

    This is exactly the situation. All the functions within the wrapper are related and some share a common variable.

    Thanks for the input!

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".