What is Closure in JavaScript?

Don’t tell me the moon is shining; show me the glint of light on broken glass.

A Closure in JavaScript, where an inner function has access to the outer(enclosing) function’s variable.

Closure Simple Example

Here we have two functions:

Let’s see step by step what happens when the outer() function is invoked

  1. Variable b is created in outer() function, and its value is set to 10.
  2. The next line is a function declaration, so nothing to execute.
  3. On the last line, it return inner which is nothing but the returning function.
    Note: The return statement does not execute the inner function – a function is execute only when followed by (), but rather the return statement return the entire body of function.
  4. Once function outer finished execution all the within the scope of outer() now no longer exist.

But,

Inner function preserve the scope chain of the enclosing function at the time the enclosing function was executed, and thus can access the enclosing function’s variable.

In our Example

The inner function had preserved the value of b=10 when the outer() function was executed, and continued to preserve(Closure) it.

Value of b=10 is preserved in the Closure even after the outer() function completes its execution.


Thanks to read

Harish Sharma

Known Technical

Thank you so much to be here and just to read my blog post. If you really love this post. Kindly share it with your friend's circle.

If you've really like my above post then, please share it to on below media

Write to Me

In case, if you like my portfolio


Harish Sharma on Facebook    Harish Sharma on Twitter    Harish Sharma on Instagram    Harish Sharma on LinkedIn    Harish Sharma's Youtube Channel

Go to Top