What are Closures in JavaScript?

Read full article on the Infragistics Blog

A JavaScript closure is a function which remembers the environment in which it was created. We can think of it as an object with one method and private variables. JavaScript closures are a special kind of object which contains the function and the local scope of the function with all the variables (environment) when the closure was created.

image

To understand closures, first we need to understand SCOPING in the JavaScript. We can create a variable or a function in three levels of scoping,

  1. Global Scope
  2. Function or local scope
  3. Lexical scope

I have written in details about scoping here, but let’s take a brief walkthrough of scoping before getting into closures.

Scopes in JavaScript

As soon as we create a variable, it is in a Global Scope. So, if we have created a variable which is not inside any function, it is in a global scope.

Read full article on the Infragistics Blog

2 responses to “What are Closures in JavaScript?”

  1. […] What are Closures in JavaScript? (Dhananjay Kumar) […]

  2. […] What are Closures in JavaScript? (Dhananjay Kumar) […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com