javascript interactive

JavaScript Interactive — a console crash course


3.3 Nested Functions

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
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

  
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 variable (and function) 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.
>>>

Index 1 2 3 4 5 6 7 8 9