What Is a Nested Function?
Nested functions are much like nested loops. They occur when one function is nested inside the other. The inner function is private to the outer function. We discussed closures earlier – binding these variables with a closure allows nested functions to "inherit" the arguments and values of the other function. Understanding what function can access the other's variables is a unique relationship.
Nested functions and closures
You may nest a function within another function. The nested (inner) function is private to its containing (outer) function.
It also forms a closure. A closure is an expression (most commonly, a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.
To summarize:
- The inner function can be accessed only from statements in the outer function.
- The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.
The following example shows nested functions:
function addSquares(a, b) { function square(x) { return x * x; } return square(a) + square(b); } console.log(addSquares(2, 3)); // 13 console.log(addSquares(3, 4)); // 25 console.log(addSquares(4, 5)); // 41
Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:
function outside(x) { function inside(y) { return x + y; } return inside; } const fnInside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it console.log(fnInside(5)); // 8 console.log(outside(3)(5)); // 8
Source: Mozilla, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#nested_functions_and_closures
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.