Since the beginning of Ask Dan a javascript question, I received a bunch of questions. Here's the first one I received. It's from Andrew Worcester.

There seems (to me anyway) to be an overuse of the “new” syntax in libraries. If I create an Ajax object is there a functional benefit to using: “new Ajax.Request(options)” verses something like “sendAjaxRequest(options)” It seems to me that by using “new” causes more hassle because you need to be sure the objects are properly disposed of. So is there a performance or functional benefit to this technique?
I had a hard time understanding the question (and I was too ass hole to ask…) so I'll rephrase it in another way : is there a benefit from using object-oriented techniques VS procedural in javascript?

Procedural in javascript

Though javascript was not a procedural language from the start, it has been overused as such in the beginning (and it's still is). That may be because people didn't bother learning javascript and they copy/pasted functions from sites that offers low-quality javascript snippet. All they did was “hacking” the poorly written code to suit their needs. This technique worked for a long time but with the use of ajax and DHTML, it's nearly impossible to have clean code that is not buggy and dirty.

Object-oriented in javascript

The new statement necessary implies the use of objects in javascript. You can have basic information about object in How to create objects in object-oriented javascript and in with the articles tagged Object-oriented of this site.

The benefit of object-oriented

There is one major benefit about object-oriented that creates a lot of other benefits : the cleanliness of the code. The other benefits from that are : the code is easier to maintain, to modify, to read and to explain.

OO applied

I'll apply it to an example. I want to alert the sound of cat by ajax.

In a procedural way, you'll approximatively have

// Global variable
  ajaxRequest = null;

function sendCatSoundAjaxRequest() { ajaxRequest = new XMLHttpRequest(); // Create the request in the global var // ... code for request ... }

function receiveCatSoundAjaxRequest() { // The sound is in clear text in the response alert(ajaxRequest.responseText); }

The problems? You have a global variable to keep track of the ajax request. Because it could be use by every other functions that need ajax, you can't make more than one request at a time. Also, there are nothing that binds the two methods together apart their names that are look alike. Now, just think of the code when you have 5 or 6 different type of requests. Your code will look like garbage.

In a object-oriented way, you would all write this ugly code in a separated object. Your main call to see the sound of a cat could be something like

var cat = new Cat();
The code from above still exists somewhere but the complexity is now hidden behind the Cat class.