Rangle Up Variables with JavaScript Closures

Using global variables in JavaScript is bad and can tick off other developers.  Use Closures to group your variables with proper scope and stop watching your back in JavaScript User Group meetings.

Here’s what I mean:

When you make a variable or function in JavaScript by default it’s defined on the global object and it can be accessed from anywhere.  Now we all know global objects are BAD – The names can conflict with other libraries, increase memory usage, make debugging a huge pain, etc. In JavaScript, the answer is to “enclose” your variables in a function.  The cool cats call this a “Closure.”

Here’s what I do:

var DirksApp = DirksApp || {};

(function ()
{
     var privateVariable = "I'm Private!";
     this.publicVariable = "I'm Public to the World!";
}).apply(DirksApp);

console.log(DirksApp.publicVariable);    //prints: I'm Public to the World!
console.log(DirksApp.privateVariable);   //prints: undefined

Instead of creating privateVariable and publicVariable in the global namespace, I’ve enclosed it in an “object” called DirksApp.  By declaring privateVariable with var it is only accessible from the inside of DirksApp.  Declaring publicVariable on this makes it publicly accessible off of DirksApp.

Just remember:

  • var for private
  • this for public

The initialization var DirksApp = DirksApp || {}; and apply(DirksApp) pieces allow the same Closure to be used in multiple files and will combine the objects. You’ll appreciate this when your application gets bigger and you want to split the code up into module files. The JavaScript apply method also sets “this” inside the closure to DirksApp, that’s why applying a new function on “this” assigns it as a public function on DirksApp.

You may have to read that last paragraph again. I was confused even writing it.  And there’s definitely more to it, but this is a quick and dirty tutorial.  Look up JavaScript Scope and IIFEs (iffys) for more info.

So, please, stop polluting the global namespace. You can start by using Closures to make your JavaScript code a bit more maintainable and you’ll make more JavaScript friends in the process.

Special thanks to Paul Sanchez, @basicdays, who presented similar content for the Milwaukee JavaScript User Group and gave me the oomph to get this article out the door.


Posted

in

,

by

Tags:

Comments

Leave a Reply

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