“var” and JS Global Scope

If you assign a value to a variable in javascript without first declaring that variable with var, it goes into the global scope.

So if, within a module, I do something like this:

var MyModule = function() {
   var _public = {};

   var doSomething = function() {
      alert("foo");
   };

   doSomethingElse = function() {
      alert("bar");
   };

   _public.init = function(options) {
      _public.options = options;
   }

   return _public;
} ();

Then the following things are true:

  • _public lives inside the scope of MyModule.
  • _public.init is inside public, so it’s within MyModule, and I can call MyModule.init() to invoke it.
  • doSomething is a private function in MyModule.
  • doSomethingElse is a function in the global scope.

We want to minimize the amount of junk that’s in the global scope, lest we run into some very confusing bugs resulting from naming collisions.

And this has been today’s Fun with Javascript.