Nested functions
Just as with loops, if
statements, and actually all other building blocks, we can have functions inside functions. This phenomenon is called nested functions:
function doOuterFunctionStuff(nr) {
console.log("Outer function");
doInnerFunctionStuff(nr);
function doInnerFunctionStuff(x) {
console.log(x + 7);
console.log("I can access outer variables:", nr);
}
}
doOuterFunctionStuff(2);
This will output:
Outer function
9
I can access outer variables: 2
As you can see, the outer function is calling its nested function. This nested function has access to the variables of the parent. The other way around, this is not the case. Variables defined inside the inner function have function scope. This means they are accessible inside the function where they are defined, which is in this case the inner function. Thus, this will throw a ReferenceError
:
function doOuterFunctionStuff(nr) {
doInnerFunctionStuff(nr);
function...