9

What are the disadvantages to nesting a function within a nested function within a nested function...

Here's an example:

JS/jQuery:

function one() {

    // do something

    function two() {

        // do something

        function three() {

            // do something

            function four() {

                // do something

            }

        }

    }
}
  • 2
    no, there's nothing wrong with that at all, and in js, it's usually a good thing. – dandavis Jan 08 '17 at 17:16
  • 2
    http://i.imgur.com/BtjZedW.jpg – BrunoLM Jan 08 '17 at 17:38
  • the inside functions may not be a [pure function](https://en.wikipedia.org/wiki/Pure_function), if they rely on closure variables. – Nina Scholz Jan 08 '17 at 17:41
  • 2
    If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling. If you need a closure or don't want to pollute your namespace, nest it. – Paul S. Jan 08 '17 at 19:02

2 Answers2

2

One disadvantage of declaring a nested function is the fact that it will be created inside function's environment every time you call the parent function.

In theory, this could decrease performance if the parent function is called frequently.

But, nested functions are very much used in Javascript. For example, closures are extremely powerful and should be understood by all JavaScript developers.

More about closures

Armen Michaeli
  • 8,625
  • 8
  • 58
  • 95
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
2

Nested functions have access to their parent scope so you could change state in a parent's scope from a deeply nested function. For example

function one() {
  var a = 1;
  two(); // a = 4

  function two() {  
    var b = 2;
    three(); // b = 4

    function three() {
      var c = 3;
      four(); // c = 4

      function four() {
        a = 4;
        b = 4;
        c = 4;
      }
    }  
  }
}

On one hand this is pretty powerful. On the other hand it can easily get sloppy and hard to reason about because you have to make sure any child function hasn't changed a value in any of its parents.

If you stick to not nesting your functions you won't have to worry that the state inside your function is being changed from inside of a nested function.

function one() {
  var a = 1;
  two(); // a = 1
}

function two() {  
  var b = 2;
  three(); // b = 2
}

function three() {
  var c = 3;
  four(); // c = 3
}  

function four() {
  a = 4;
  b = 4;
  c = 4;
}
Emil Ng
  • 31
  • 4