August 12th 2021
· 3 min read
Closure is when an inner function has access to its parent function’s scope even when the outer function is done executing. Every time a function is created, a closure is created with it. The variables in this outer function are accessible by the inner function even when the outer function has returned.
The main benefit or usage of closures is in data privacy. The private variables of a function are not accessible outside its scope. But with a closure you bind these variables with the inner function so using the inner function you can access them even after the parent function is no longer active. Declaring the variables as global exposes them to the risk of manipulation, using closures they can only be accessed by the closed inner functions thus ensuring privacy.
Callbacks are when a function is passed as an argument to another function. The calling function accepts reference to another function as a parameter passed to it. Callbacks can be executed synchronously or asynchronously.
If we want to define the functions to be executed in a synchronous manner, callbacks come into play. Using callbacks we can pass the function that should be executed later as an argument to the function which should be executed first. The calling function will execute the callback after it has completed its operation. Consequently, we control the order in which the functions are executed.
Below is a short video explaining these two concepts using an example.