So what is a closure? A closure is a function bundled with references to its surrounding state. In clearer terms we could say that a closure is a function inside an outer function that has access to the outer function’s scope. The closure has access to its own variables, the outer function’s variables and the global variables. Just reading this might not make much sense so let’s look at an example.
Closures let you associate data with a function that operates on that data. This can be compared to how in object-oriented programming objects allow you to associate data with methods. As you can see we can save the closure into two different variables and the operation on different values. Even though the outer function already ran the environment within it is still accessible to the inner function because it was saved in memory. The environment is stored by the closure for its own later use.
I hope this will help anyone out there understand the basics of closures. It is a very interesting topic and there is still many more things I need to learn about it. Practicing with them will only help more. Questions about closures are frequently asked during interviews so it is very important to understand this concept in order to ace the interview. Happy coding! 😎