Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Nesting functions: Good or Bad?

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #159341
    Rugg
    Participant

    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();
    
    #159594
    noahgelman
    Participant

    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

    #159601
    __
    Participant

    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.

    #159656
    Rugg
    Participant

    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)
  • The forum ‘JavaScript’ is closed to new topics and replies.