Closures and Callbacks in Javascript

Image of article writer

Saleha Khan

Closures and Callbacks in Javascript

In this article, we will briefly explore two important concepts in Javascript: Closures and Callbacks. Let's take a quick look at what they are and also their usage.


Closures

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

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.


Let's look at one of the areas where callbacks can prove to be useful. JavaScript executes code top down in a synchronous manner. But if it has to wait for an operation to complete, it will execute the rest of the code while waiting. In that case we cannot control the flow of execution of functions as they are not executed sequentially as one would expect. 

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.

Be the first to comment on this article

In order to comment, please enter your information below.