This is the Advanced JavaScript article series; in this series, we are learning various important concepts of the JavaScript language. We have already covered the following topics, you can visit them.
In this article, we will cover one of the most interesting features of JavaScript called "closure". The feature might be a little confusing to developers but when we try to develop a JavaScript library, this feature might help us.
The fundamental idea behind "closure" is, the function will return another function rather than returning any other primitive or user-defined data type. So, try to understand it.
Understand Outer and inner function
So, when we are talking about a function that returns another function, that sounds like a nested function. The outer-most function that returns another function is called the outer function and the function that will be returned is called the inner function. Have a look at the following example.
Implement simple closure
In this example, at first, we are defining fun1() that is an anonymous function and the function returns another function.
Here is sample output
Pass value to both outer and inner function
If needed, we can pass a value to an inner function via an outer function. In the following example we are passing "value1" to the outer-most function and "value2" to the inner-most/span> function. Then we are checking whether both values are the same. If the same then the message will be returned.