Console Learner — An interactive JavaScript course.


3.3 Nested Functions

>>>
function squareDist(x, y) {
    function square(num) {
        return num * num;
    }
    return square(x) + square(y);
}

  
A nested function can also be declared inside another function. Here the local square() function is used as a helper inside squareDist().
>>>
square
ReferenceError: Can't find variable: square
The nested function is only visible inside its parent function.
>>>
squareDist(2, 3)
13
The code in the squareDist() function can refer to the square function (variable) as expected. Nested functions are sometimes useful to avoid code repetition.
>>>
function outer() {
    function inner() {
        return 4711;
    }
    inner.count = (inner.count || 0) + 1;
    return inner.count;
}

  
Although a nested function looks like a top-level function declaration, it is actually a function statement (similar to an anonymous function expression). The returned value of the inner.counter property illustrate what this means.
>>>
outer()
1
In the first call, the returned value is 1 as expected.
>>>
outer()
1
But all outer() calls keep returning 1, which shows that the inner() function is recreated on every call to outer(). This behavior is important to recognize, since it sometimes leads to inefficiencies in frequently used code.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.