Introduction to Nested Functions
Learn how to create and correctly call nested/inner functions.
We've already learnt that functions have their own scope, the local scope.
You can use the local scope to create variables that are accessible only within the function.
This is not limited to just variables.
You can also create another function inside your function.
In this example, we create a function called inner that is nested inside a function called outer:
When using nested functions, the same rules for global and local scope apply.
Since inner is defined inside the local scope of outer, it cannot be called from outside of outer. If we try to do so, we will encounter an error:
To execute a nested function, you must call it from within the outer function. After that, you call the outer function to run everything:
What will be the output?
What will be the output?
What will be the output?
Remember that you can use the global
keyword to declare a variable as global within a local scope:
This is only limited to variables and does not work for nested functions. Let's see what happens if we try: