Search code examples
javascriptfunctionclient-side-scripting

Nested Function and Closures


What is the difference between Nested Function and Closures in JavaScript or both are same? There is any functional difference?


Solution

  • There is a difference. Closure is observed when an inner function is returned outside of it's lexical scope but still maintains a connection to its lexical environment. Take a look at the example below.

    function addOne() {
      var x = 1;
       function bar() {
        console.log(++x);
      }
    	return bar;
    }
    
    var adder = addOne();
    adder(); // 2
    adder(); // 3
    adder(); // 4

    From the above, we can see addOne() is called and it returns the function bar which gets stored in adder. Typically you would expect that the internal state of addOne() call (execution context's variable environment) would be garbage collected but, because there is a reference to the bar function on the outside, the internal state of the addOne() call is preserved. When adder is called, it's going update the var x because of closure.

    function addOne() {
      var x = 1;
       function bar() {
        console.log(++x);
      }
      bar();
    }
    
    var adder = addOne(); // 2
    adder() // Uncaught TypeError: adder is not a function

    With the above code, function bar merely nested inside of function addOne. When function addOne gets called, an execution context is created, which creates var x and function bar. when bar gets called, it's able to update the value of x because of lexical scope. When the addOne function is done executing, the execution context goes away and the x and bar gets garbage collected.

    In short, with closures, the internal state of the outer function's execution context gets preserved but with nested functions, the outer function's execution context goes away and the variables and functions that were created get garbage collected.