In Javascript, it is possible to nest functions – so that functions may be defined inside other functions.
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.
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.
Would you like to thankProgrammerInterview.com for being a helpful free resource?Then why not tell a friend about us, orsimply add a link to this page from your webpage using the HTML below.
Link to this page:
Please bookmark with social media, your votes are noticed and appreciated: