In JavaScript, you can have functions inside other functions. This setup can be useful in some scenarios. For instance, an inner function can be used to perform a specific task that’s only relevant within the outer function, keeping your code more organized and easier to read. They can also be used to create closures, which can encapsulate private variables and functions. (More on this later).
Let’s look at a simple example where one function is nested inside another:
In this example, outer
is a function that has another function inner
inside it. inner
has its own variables, and it can also access and modify variables from outer
.
Inner functions can access and change the variables in their parent function. This is shown in the following example:
Here, the inner
function modifies the num
variable that’s defined in outer
. After calling inner
, you see the updated value of num
.
Inner functions are great for when you have helper functions that you don’t need anywhere else except inside a specific function. By keeping these helper functions nested, you prevent them from being accessible from outside where they’re not needed. This helps in managing the scope of functions and variables, keeping everything organized and secure.
Next, we will explore other use cases of inner functions, such as closures and currying.