US & Canada: 877 849 1850
International: +1 678 648 3113

Accelebrate Blog

ACCELERATED LEARNING, CELEBRATED RESULTS

Closures in JavaScript

What I wish I had picked up in Introduction to JavaScript. Pt 2

So, JavaScript is really a simple language. It is a language that is straight forward: what you see is what you get. Here is the problem: Closures are being used all over the place in modern JavaScript, but just because I see them does not mean I get them. This “simple” onClick and mouseOver language has got some sting.

This article is going to introduce a concept which (in my opinion) can be difficult to digest by itself, but is a fundamental (if not THE fundamental) building block to understanding the syntax that is very often used in “modern” JavaScript pages.

The “What” Closure

Obligatory simplified example:

<script language="JavaScript">
var validateForm=function(){
    var checkValue = function(pattern,value){
    }
    //The following calls work. They can "see" the checkValue function
    if (checkValue(//,document.getElementByID(''.) && checkValue(//,form.){
        return true;
    }
    else { return false }
}
// checkValue(//,'abc');  // This fails. – can't "see" the function
</script>

The checkValue variable is available only within the outer validateForm function. The checkValue is a closure. A function defined within another function is a closure. Functions that are defined within another function can “see” the variables within that function – var variables, arguments, and global variables.

Simple. A closure is a function defined within another function. That is pretty simple. The “what” is the easy part. The harder part is the “why” — and, even harder, all the nuances that they enable.

The “Why” Closures

There are many code designs that we can use because of closures. We will start with the building blocks and over the next few articles, show some fantastic applications of this pattern to achieve some mind-blowing code.

First back to var. Free Choice.

Remember the var keyword? The var keyword scopes a variable to the function within which it is defined.

In a prior article, we played with var and saw the dangers of scoping variables in the global namespace. Here it is again: A closure is not automatically in the global namespace. In this example, the checkValue is a variable scoped to the outer validateForm function. In the above example, the only global variable is the validateForm variable.

Chew on this. What would removing the var in front of checkValue mean?

var validateForm=function(){
   # NO var keyword below
   checkValue = function(pattern,value){
   }
   //The following calls work. They can "see" the checkValue function
   if (checkValue(//,document.getElementByID(''.) && checkValue(//,form.){
      return true;
   }
   else { return false }
}

Answer: Removing the var has made that function visible everywhere. We get to choose. We can choose to add a variable to either function scope of global scope. I like choice.

Second: More var. Private variables

<script language="JavaScript">
var createMessage = function(msg){
    var privateMessage = msg
    var show = function(){
        console.log(privateMessage);
    }
    return {'show':show}
}
var happyMessage = createMessage('Hello Friends');
var sadMessage = createMessage('Goodbye Friends');
happyMessage.show();
sadMessage.show();
// This is no good.  This will not work.
//console.log(privateMessage);
</script>

The privateMessage variable is created as a var variable within the createMessage function. It is not accessible outside that function. The closure (show) is making a reference to that variable. We can see variables from the outer function inside a closure. In fact, it gets better. That state – the state of that variable – stays around as long as we hold reference to the show variable. We are passing the show variable back out. That show function is able to be invoked from outside the createMessage function. The specific state of the privateMmessage variable is retained on the “stack” so the show function has access to it.

Did you catch that? We created a private variable that is only accessible from the show function. Do you suppose we can modify that private value? Check it out:

<script language="JavaScript">
var createMessage = function(msg){
    var privatemessage = msg
    var show = function(){
        console.log(privatemessage);
    }
    var setValue = function(msg){
        privatemessage = msg;
    }
    return {'show':show,'setValue':setValue}
}
var happyMessage = createMessage('Hello Friends');
var sadMessage = createMessage('Goodbye Friends');
happyMessage.show();
sadMessage.show();
happyMessage.setValue('Wahoo Glad you are still here!');
happyMessage.show();
sadMessage.show();
</script>

Don’t look now, but I believe this is an implementation of encapsulation; Variable encapsulation in JavaScript using closures.

There are MANY more nuggets that this closure concept enables. Keep an eye out for a few more articles that will dive much deeper into the “Why” and patterns around this.


 

Author: Todd Wright, one of Accelebrate’s instructors

Accelebrate offers private JavaScript training for groups and instructor-led online JavaScript classes for individuals.

Categories: JavaScript Articles
Tags: , ,

Leave a Reply

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

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

*



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Please contact us for GSA pricing.
Contract #GS-35F-0307T

Please see our complete list of
Microsoft Official Courses