×


Closures in JavaScript

A closure is the combination of a function and the lexical environment within which that function was declared. We will take a detailed look in to closures using the following examples.

In this example,you can see that variable a is in Global scope.The variable a is available inside the example() function so that , we don’t have to pass it as an argument to the example() function.
Now if you do a console.dir on the function example() (console.dir is the way to see all the properties of a specified javascipt) ,you can see that there is a scope property which has global value a.

CLOSURE

Now,we define a function inside a function and do the same addition operation given in the previous example.Here the scope of variable a and variable passed ,is the function example().The variable a and variable passed is available inside the inner function exampleinner().

If you do a console.dir on the inner function exampleinner(), we can see that there is a property called closure which has the values of variable passed and variable a.

 

So what closure means is that the inner function will have access to the scope of the outer function(FUNCTION INSIDE FUNCTION) or other words we can call it function with preserved data.

Adding values to the global object is not a good idea.With closures we can avoid declaring Global variables

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *