Just as we can place loops inside loops or if statements inside if statements, we can also write functions inside of other functions.
This powerful feature is known as Nested Functions.
Understanding nested functions is essential for mastering JavaScript because it introduces important rules about variable scope and how different parts of your code can interact with each other.
Let's look at a simple example of an outer function containing an inner function.
Notice how the inner function (doInnerFunctionStuff) is defined entirely inside the curly braces {} of the outer function (doOuterFunctionStuff).
function doOuterFunctionStuff(nr) {
console.log("Outer function");
// Calling the nested function
doInnerFunctionStuff(nr);
// Defining the nested function
function doInnerFunctionStuff(x) {
console.log(x + 7);
console.log("I can access outer variables:", nr);
}
}
doOuterFunctionStuff(2);
As you can see, the outer function is successfully calling its nested function. Most importantly, this nested function has access to the variables of the parent function. It easily logged the outer variable nr.
While an inner function can access the outer function's variables, the reverse is not true.
Variables defined inside the inner function have function scope. This means they are only accessible inside the specific function where they are defined. The outer function cannot "see" inside the inner function.
Look at what happens if the outer function tries to log the inner function's variable z:
function doOuterFunctionStuff(nr) {
doInnerFunctionStuff(nr);
function doInnerFunctionStuff(x) {
let z = 10; // 'z' is scoped to the inner function
}
// This will throw an error!
console.log("Not accessible:", z);
}
doOuterFunctionStuff(2);
This throws a ReferenceError: z is not defined because z simply does not exist in the outer function's scope.
What do you think will happen if we try to call the inner function completely outside of the outer function?
function doOuterFunctionStuff(nr) {
function doInnerFunctionStuff(x) {
let z = 10;
}
}
// Trying to call the inner function from the outside
doInnerFunctionStuff(3);
Warning: This will also throw a ReferenceError: doInnerFunctionStuff is not defined.
The function doInnerFunctionStuff() is defined inside the outer function. This means that its existence is completely scoped inside doOuterFunctionStuff().
Outside of the main function, the inner function is completely out of scope and invisible to the rest of your JavaScript program.
Which of the following statements about nested functions is TRUE?