Javascript closures are considered to be advanced stuff, and not many concern about this tehnique. That’s really a shame, because closures are the answer to the problem of how to bind variables to functions that are called at a later time. I actually found the need to use this technique while working on a project.

A closure takes place when a created function binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.

Here is an simple example:

  1. function say(name) {
  2.   var text = name; // variable
  3.   return function() { alert(text); }
  4. }
  5. say('Hello')();

In JavaScript, when we declare a function within another function, then the local variables can remain accessable after returning from the called function. Above, when we call the function say(); we get returned a anonymous function, that we call – (‘Hello’)() – and in that function we have access to variables in the first functions scope.

I know that it may not make a lot of sense but let me give you a real life example, where I had to use closures.

So the issue was this, I had to call a function encryptData to which I had to give a string and a callback, that would respond with an encryption of the string that I gave, something like this:

  1. encryptData(original_string,function(encrypted){
  2.   alert(encrypted)
  3. });

Only issue was that I wanted to also show the original string, keep in mind that i called this function multiple times for different strings, and the encrypted string didn’t necessarily come in the same order I’ve sent them. my custom essay writer

So what I wanted to do is something like this(the example will not work):

  1. encryptData(original_string,function(encrypted){
  2.   alert(encrypted + " Original:" + original_string)
  3. });

Problem that in the anonymous function the original_string was not accesible anymore, so the fix was using closure, like this:

  1. encryptData(original_string,function(original_string){
  2. return function(encrypted){alert(encrypted + " Original:" + original_string);}
  3. }(original_string));

Now in the anonymous function that I send as a callback I have access to the original string.And this is javascript closure.