jQuery: the false myth of procedural programming vs object-oriented programming

jQuery: the false myth of procedural programming vs object-oriented programming

The conflict between OO programming and procedural programming in jQuery is a false myth.

There are some common misconceptions about procedural programming in jQuery that need to be cleared out. Generally speaking, procedural programming is not necessarily a synonymous of spaghetti coding. There are several examples of OO code that is even more difficult to read and maintain than a jQuery script which makes use of the procedural approach. In this article I'll try to make things clearer in order to help you when it comes to choose between the OO approach and the procedural approach.

Simple tasks require simple code

I spend most of my time by fixing broken code on many websites. Since the overwhelming majority of these sites is built with WordPress, this means fixing the JavaScript code of many themes.

The first thing to do is to check out the main JavaScript file of the current theme after watching carefully the reports of the browser's console.

WordPress themes are a perfect example of the existing distinction between OO and procedural code. OO code may look like this:


(function( $ ) {

  $.ThemeClass = function( options ) {
    // initialization
  };
  $.ThemeClass.prototype = {
    // public and private method and properties
  };
  $(function() {
    var themeClass = new $.ThemeClass();
    // or instantiated like a plugin
  });
})( jQuery );

Instead, procedural code may look as follows:


(function( $ ) {

  function initSlider() {
    $( ".slider" ).flexslider();
  }
  
  function initTabs() {
    $( ".tabs" ).tabs();
  }

  // other functions

  $(function() {
    initSlider();
    initTabs();
    // other functions
  });
})( jQuery );

Different tasks require different code. In the first example our author has to handle complex tasks which require a more structured approach so he decides to follow the OO approach.

In the second example, instead, our author simply needs to initialize a couple of jQuery plugins so he follows the procedural approach.

Who is right? Both. Because everything depends on the complexity of the goal you want to achieve. Remember: simple tasks require simple code, whereas complex tasks require a more complex approach.

Conclusions

The conflict between OO programming and procedural programming in jQuery is a false myth. There are only two types of code in jQuery: a well-written code and a badly written code. This is the only difference that matters from a practical point of view.