jQuery: Protecting or hiding variables / functions in a specific local scope

As everyone who’s well trained in software engineering would agree, that one of the principle of writing predictable code is to separate and hide something within only the scope that it’s needed. Controlled access to and from the outside world brings predictability and accountability of your code thus better debugging.

In jQuery, you need constantly extending the native features by writing extra plugins and adding new functions:

var newMethods = {
  check       : function() { ... },
  uncheck     : function() { ... },
  toggleCheck : function() { ... }
};
jQuery.each(newMethods, function(i) {
  jQuery.fn[i] = this;
});

Without proper fencing, the variable containing 3 functions newMethods is everything but protected from the global scope (outside world), increaseing the complexity of the code and difficulty in debugging. To solve this problem, you will want to embrace the code in an anonymous function.

(function() {
  var newMethods = {
    check       : function() { ... },
    uncheck     : function() { ... },
    toggleCheck : function() { ... }
  };
  jQuery.each(newMethods, function(i) {
    jQuery.fn[i] = this;
  });
})();
Scroll to Top