Closure is a simple concept that tends to be overly explained. You like keeping things simple and organized, right? (Nod). Good. Now keep your variables within it’s respective code block and everything will be all right.

Exciting things can happen within blocks of code. From validating form data to making unicorns pop out of nowhere, blocks of code can be awesome. But if you piss off code blocks by introducing unwanted global variables, then it’s gonna kick your ass and step on your shoes.

Code blocks in JavaScript are defined by a set of opening and closing curly braces {//where the magic happens}. Variables defined within these braces (using reserved word var) live privately within block; they can only be modified by code within the current and child code blocks.
Let’s look at the following:

var wack_mc = "Yo yo. A-yo check it. Yo.";
var you_cant_touch_this = function(){

var hammer = "Yo, I told you. You can't touch this.";
alert(hammer);

}(); // The parenthesis here invokes (or calls) the function immediately.
// You can alternatively call this function by using: you_cant_touch_this();

There are three variables defined:

  1. wack_mc : Implied global variable of type string
  2. you_cant_touch_this : A typeof function variable
  3. hammer : a string variable that is enclosed within the you_cant_touch_this code block

Sounds simple…

It is. Now lets say you had the cojones to actually step up hammer and kick a flow; change the value of the hammer variable by overwriting it with your own value. Now that’s gangsta.

hammer = "Your rhymes are so wack, I'm bout to have a heart-attack!";

If you were to put the code above outside of the you_cant_touch_this block, nothing would happen; the value of hammer will not be altered because it is defined within  the warm and snugly closure of the you_cant_touch_this function. Because you_cant_touch_this is a function variable, you can use the braces required for functions to define variables that can be hidden from code outside the function code block.

At this point hammer is very upset. He can’t believe that someone would actually try to step to him with such atrocity. This is what he did:

wack_mc = "If you can't groove to this, then you're probably dead.";

Guess what happens. Yeah, that’s right. wack_mc had his ass handed to him by hammer. The wack_mc variable was altered because it wasn’t wrapped in the braces of closure. If this was the only code provided, it is implied that the wack_mc variable can be globally accessed by other code in the application, thus being susceptible to getting overwritten by code after it’s declaration assignment.

Using closure in your applications will not only make it easy to read and understand, it is the safest way to ensure that your variables do what you intend on them doing: being awesome.

Advertisements