Beginners guide to Closure in Javascript

Closures are a fundamental concept in Javascript which is quite a confusing concept to understand. What are closures? is a mandatory question asked in Javascript technical interviews.

So in this article, I will help you understand Closures.

Closure is a function in which has access to its outer function scope even after the outer function is executed.

Let's take an example

function outerFunction() {
let outerVariable = "Hello";  // variable declared in outer function scope
   return function closureFunction() {
        let innerVariable = "World";
       console.log(outerVariable + " " + innerVariable); // variable accessed in the inner function

let foo =  outerFunction();

foo(); // Can you guess the output ?

The output of the code is: "Hello World"

In the above example, the function outerFunction has a variable called outerVariable which is accessible to the closureFunction even after the function has been returned ( let foo = outerFunction(); ) . Here the inner function (closureFunction) can access the variables defined in its own scope, the outer function’s scope.

All you need to know about closures is that when you have a function declared inside another function, the inner function has access to variables and the scope of the outer function, even if the outer function finishes execution.

No Comments Yet