Spaghetti code in jQuery

Spaghetti code in jQuery

How to avoid some common coding mistakes when using jQuery.

Even with jQuery you can actually write spaghetti code. To be honest, it's very common. The problem is that jQuery tends to be very loose when it comes to organize your code. The selector chain allows you to write entire blocks of code containing several routines joined together and it's very difficult to track, debug and reorganize this kind of code. Let's see some examples of spaghetti code in jQuery.

As mentioned above, the most common example of spaghetti code in jQuery is a virtually infinite selector chain:

$('#test').addClass('test').parent().find('li').addClass('item').css('list-style', 'none').end().click(function() {

	//...

});

This chain has been intentionally written without proper formatting just to show you how things can get complicated in jQuery when you overuse the features offered by this library.

Another example is the overuse of general-purpose functions instead of objects:

$(function() {
var validateForm = function(form) {

	form = $(form);
	
	form.submit(function(e) {
	
		//...
	
	});

};
});

The overuse of functions makes your code harder to be reused in other contexts and also leads to potential conflicts with other general functions used by third-party code.

Another sign of a poorly written jQuery code is the use of cryptic and non-descriptive variable names. Surprisingly, many jQuery plugins use this approach, thus making almost impossible to modify the original code without breaking the plugin's core.

Also inserting several script elements on your pages should be avoided. This means that you didn't plan your code to allow for further modifications and insertions.

I see many examples, demo and plugins that still use some DOM Level 0 coding practices, such as inserting event handlers in the markup. This is a pure and simple mistake.

Finally, when you use objects, you should always choose carefully the visibility of your methods and properties. A common error is to define a single initialization method and a plethora of private methods. What happens if you need to interact with the document using your object? With a single public method you can only initialize your object, but you can't perform other interactions.

It's always recommended to plan your code by addressing the actual needs of your site or application, even in the future.