New Toronto Group
 - New Toronto Group

Start using closures with your AngularJS, EmberJS code, and other JavaScript.

| Posted on September 08th, 2014 by Doug Riches


Closures are one of the most powerful tools in JavaScript; they can help you write faster, cleaner, and safer code. No matter if you are using AngularJS, EmberJS, JQuery or another framework, closures are an invaluable tool you should be taking advantage of. Lets review the how and why of closures, and give you some examples to play with on your own.

First off, let’s take a look at the word “closure”. It was first coined in 1964 to refer to an anonymous function (lambda expression) or named function that has non-local variable references from outside it’s own scope “closed in” to the function instance.

Confusing a bit? Take a look at a simple example:

 Check it out and play around working in a JavaScript REPL:

http://repl.it/YJ5

 

 Lets take a look at what happens in the example above:

 

1)    We have the function “createClosure” that accepts input in the parameter “x”

2)    The function “createClosure” has a function called “closure” that is inside the “createClosure”  scope, that is to say: “closure” function has access to all it’s parent’s variables.

3)    The inner function “closure” accepts input in the parameter “y”

4)    This is where the magic starts to happen… Inside the “closure” function we reference “x”, which belongs to “createClosure”, the parent.

5)    The “createClosure” function returns the function “closure” to the caller. The value of “x” is now enclosed within the “closure” function and will persist now that “createClosure” has finished executing.

6)    We assign the result (function) of createClosure with the parameter “hello” to the variable “greet”.

7)    We assign a second variable “farewell” with another new instance of our “closure” function and a different parameter “goodbye”

 

Note the results; the value we passed to the function “createClosure” is retained by the instance of “closure” forever.

 Run the session in the link above and try it for yourself. You are not limited to just one variable to enclose you can create a closure with as many objects as you want.

 

Syntax of a closure

There are two main ways you can create a closure either a single instance or multiple instances as we have illustrated above:

 Multiple Instances: we want to create different closures based on some sort of input. 

1)    Create a function that contains your data to be enclosed

function createClosure(x) { }

2)  Add any additional variables we want the closure to have access to

var separator = '-';

3) Create an inner function that gets returned, have it reference the outer variables you created.

return function(y){

            return x + separator + y;

}

4) Every time you assign the result of createClosure() to a variable to create a new instance of the closure.

function createClosure(x) {
var separator = '-';
return function(y){
return x + separator + y;         
}
}

Call createClosure() to create new instances.

See it working: http://repl.it/YWi

Single Instance Closure: We only want to create the closure once

1)    Assign an anonymous function to a variable

var closure = function(x) { };

2)  Add any additional variables we want the closure to have access to

var separator = '-';

3) Create an inner function that gets returned, have it reference the outer variables you created.

return function(y){

            return x + separator + y;

}

4) IMPORTANT: Execute the anonymous function instead of assigning it by calling it immediately. Without this step we assign the anonymous function that creates closures to the variable. (not good)

(‘hello’)

var closure = function(x){

    var separator = '-';

            return function(y){

                        return x + separator + y;

            };

}(‘hello');

See it working: http://repl.it/YWh

So…why? 

You might ask yourself why would I want to do this. My code works just fine…

Lets look at a couple of scenarios:

1)     I want to make sure my functions and variables doesn’t get overwritten by some other code:

http://repl.it/YWR

Let’s look at an ‘evil’ function that overwrites an array we are depending on to have a set of information.

 

What’s happening here:

1)    We created an array named “animals”

2)    We have a function called “randomAnimal” that picks a random animal from our array of 4 animals

3)    Call the randomAnimal function and we get back an animal string from our list of 4 animals! yay!

4)    Someone comes along and adds some code that accidentally overwrites our array animals with a new array that has 3 values

5)    The new bad code gets executed….

6)    Now when we call our function after the “someOtherBadCode” has been called it returns animals from the wrong list!! Not good.

Solution:

Protect our data from being overwritten using closures.

http://repl.it/YWV

 

What happened here? We protected ourselves.

1)    We organized the code into public and private objects so we can keep track more easily of what we want to share and what we don’t

2)    The Animals array was created inside the private object as well as the randomNumber function

3)    The variable pub (public)  is a function that

2)     I want to make my application efficient:

Well we hope that you always want to make your applications faster. Lets take a look at how we can do that with Closures:

 

In the following example, we show another option we could have used to protect our animals array from being overwritten:

http://repl.it/YVj

 

This non-closure approach works, but the example above is slow. Why? Because EVERY time you call the function the array is allocated to memory, created used then destroyed. If this were a large array or JSON object we would have some pretty slow function calls happening..

Closures solve the problem of creating private expressions in an efficient way. We will create a single instance of the animal array that is completely protected from changes, with only a few updates to the code!

Take a look at the function randomAnimalClosure() below:

http://repl.it/YVj/1

 

 

Summary

Closures are powerful tools to use when you create your JavaScript Applications. They can make the difference between mediocre performance and excellent performance in complex applications.

Closures can:

  • Protect your code from the pollution that can happen in the global scope.
  • Make your code more efficient by only creating single instances of objects.
  • Allow you to create private objects that can not be accessed by other program code (encapsulation)

Regardless of the framework you use, closures can help you start right away encapsulating your data and methods and writing more efficient and faster code.

Posted in AngularJS, EmberJS, jQuery, JavaScript  | Comments (2)

Comments (2)

  1. Ronak:
    Oct 31, 2014 at 09:11 PM

    Hi Doug, this is a very well written blog explaining Closures in a simple manner.
    I can say, now I understand Javascript Closures!
    Regards.

  2. Simple:
    Oct 19, 2015 at 08:55 PM

    Thank you for this post. I learned a lot in a short matterof time.


Add a Comment





To use reCAPTCHA you must get an API key from http://recaptcha.net/api/getkey

Allowed tags: <b><i><br>Add a new comment: