Thursday, November 27, 2014

How to Avoid Any Global Variables in JavaScript



In JavaScript, objects and functions, are also variables. And any variable declared outside a function has global scope. You probably heard that because JavaScript is a dynamically type language global variables are bad and that they easily become source of confusion and bugs. So how can we avoid of creating any global variable, but still have our code executed?
There is such technic, it's called Immediately Invoked Function Expression (IIFE).

Suppose we have this JavaScript code:

var func = function(){
  
  console.log("entering func");
  
  var counter = 0;
  
  var innerFunc1 = function(){
    counter += 1;
    console.log("innerFunc1: " + counter);
  }
  
  var innerFunc2 = function(){
    counter += 1;
    console.log("innerFunc2: " + counter);
  }
  
  return {
    inner1: innerFunc1,
    inner2: innerFunc2,
  };
}

var f = func();
f.inner1();
f.inner2();

So here we have two global variables - func and f.
Now I'll show how to run this code without creating ANY global variable by applying IIFE.

(function() {
  var func = function() {

    console.log("entering func");

    var counter = 0;

    var innerFunc1 = function() {
      counter += 1;
      console.log("innerFunc1: " + counter);
    }

    var innerFunc2 = function() {
      counter += 1;
      console.log("innerFunc2: " + counter);
    }

    return {
      inner1: innerFunc1,
      inner2: innerFunc2,
    };
  }

  var f = func();
  f.inner1();
  f.inner2();

}());

So actually we wrapped our code inside anonymous function that immediately invokes itself or in other words Immediately Invoked Function Expression (IIFE).
The code still executes exactly as it did before but with creating no global variables at all.
Happy codding! :)

1 comment:

  1. But then how should this function make itself available to functions in other files? For example, how would something like jQuery avoid putting the jQuery() function in the global namespace?

    ReplyDelete