Understand closures in javascript


Let’s learn closures today, How closures are define how they got intialize and how they work

A closure is a function within a function that has access to the environment that it was created, which gives the ability to access the private methods of outer function to their inner function. In simple words function which is return by another function called closures.

A closure is created when you define a function — not when you execute it. Then, every time you execute that function, its already-defined closure gives it access to all the function scopes available around it.

Let’s take a look at an example

Suppose we create a addCounter function, which increase count by 1:

var counter = 0;

function addCounter(){
  counter += 1;
  return counter;
}

But the problem is that with this above code any function can change the counter value without executing addCounter() method. which is not correct

Another example:

function addCounter() {
  var counter = 0;
  function plus() {counter += 1;}
  plus();
  return counter;
}

The inner function plus() has access to the counter variable in the parent function

But when the addCounter() will get execute it will always make counter count 0. This is not our case. Our case is like we have to execute counter variable only at once, So that we increase counter by 1, Their closure will help us, We are creating below example using Immediately-invoked function expression (or IIFE, pronounced “iffy”)

var addCounter = (function () {
  var counter = 0;
  return function () {
  return counter += 1;
 }
})();

The variable addCounter is assigned to the return value of a self-invoking function. Why did we put counter in an immediately-executed anonymous function? It makes counter private, which prevents accidental changes from the outside world. Like as we did in our first example where counter variable is global

The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.

This way addCounter becomes a function. The cool part is that it can access the counter in the parent scope.

This is called a JavaScript closure. It makes it possible for a function to have “private” variables.

The counter is protected by the scope of the anonymous function, and can only be changed using the addCounter function.

Advertisements
This entry was posted in AJAX, Functional Programming, JavaScript, jQuery, Scala, Web, web application and tagged , . Bookmark the permalink.

One Response to Understand closures in javascript

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s