Does Javascript support nested functions? How do they work?
In Javascript, it is possible to nest functions – so that functions may be defined inside other functions.
Javascript Nested Functions Example
Here’s an example of what nested functions in Javascript would look like:
function circumference (radius) { // nested function: function diameter() { //note the use of "radius" - a parameter of outer function return 2*radius; } // call the nested function return Math.PI * diameter(radius); }
The function circumference calculates the circumference of a circle when given the radius as an input. You should pay special attention to the call to the inner function diameter, which will return the diameter of a circle by simply multiplying the radius by 2.
Javascript Nested Functions Scope
Nested functions have interesting scoping rules. A nested function can access any variables and parameters of the outer function(s). In our example above, you can see that the nested function – diameter – is passed the radius parameter which is a parameter defined by the outer function named circumference. This is of course because any nested function has access to the parameters of it’s outer function.