# 2 Ways to Access Nested Functions in Javascript

An “inside” look.

Say you’re constructing a nested function like so in Javascript:

function outerFunction(x) {

function innerFunction(y) {

return x + y;

}

return innerFunction;

}

Running the outerFunction returns a function.

outerFunction(8) // returns innerFunction()

What if you want to run the innerFunction? Because it is out of scope, you cannot call innerFunction directly. However, you can evaluate the return value of outerFunction like so:

outerFunction(8)(5) // returns 13

How does that work? Remember that each pair of parentheses, or (), tells Javascript to run the preceding function once. If you use multiple pairs of parentheses, you’re telling Javascript to run something multiple times. In our example, the first parentheses ran outerFunction, which returned another function: innerFunction(). The second pair of parentheses then ran innerFunction, passing any arguments from outerFunction to innerFunction:

outerFunction(8)(5) // The first () returns innerFunction but doesn't run innerFunction. The second () runs innerFunction and passes innerFunction arguments 8 and 5. InnerFunction() then returns 13.

What if you have several nested functions?

function outerFunction(x) {

function innerFunction(y) {

return x + y;

}

function anotherFunction(y) {

return x - y;

}

function yetAnotherFunction(y) {

return x * y;

}

function privateFunction(y) {

return y * y;

}

return {

innerFunction,

anotherInnerFunction,

yetAnotherInnerFunction

}

}

Running outerFunction() would return an object containing references to 3 functions. Running outerFunction()() would throw an exception because you return an object on the first evaluation (the first “()”), and objects can’t be called, or run, as functions. The second evaluation (the second “()”) will try to run the object as if it were a function… but objects are not functions so you get an error.

So how do we run one of those nested functions? This is where dot notation comes in handy.

outerFunction(8).innerFunction(5) // returns 13

As with any object in Javascript, you can use dot notation to get the value of any key in the object. In this case, we specified the innerFunction then added the () to actually run innerFunction.

Note that the object returned by outerFunction() does not include privateFunction().

outerFunction(4) // returns {

innerFunction,

anotherInnerFunction,

yetAnotherInnerFunction

}

This means we can never directly call privateFunction(). privateFunction() is locked up in a closure and can only be used from within outerFunction().

privateFunction() // throws ReferenceError: privateFunction is not defined