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.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

  • varoon10

    Thanks – it’s been fixed. The nested function now has no parameters to illustrate the fact that it can access the parameters of the outer function just by name.

  • varoon10

    You are right! Thanks for pointing this out – it’s now been fixed.

  • Qiusheng

    Wrong example

  • Bill Hsu

    add a closure example here would be better

  • Dariusz Mydlarz

    You dont show here that nested function has access to variables of the outer function. You just pass argument to nested function and use it.