Good & Bad jQuery Practices


10.1. Best Practices: Loops

  • Cache the length property in loops:
    var arrayLength = myArray.length;
    for (var i = 0; i < arrayLength; i++) {
  • Append content outside of loops
    $.each(myArray, function(index, item) {
      var newTweet = '<li>' + item + '</li>';
    var newTweet = '';
    $.each(myArray, function(index, item) {
      newTweet += '<li>' + item + '</li>';

10.2. Best Practices: Avoid Anonymous Functions

  • Anonymous functions are often used when binding event handlers.
  • However, anonymous functions are difficult to debug, maintain, test, or reuse.
  • It’s better to use object literals:
    $(document).ready(function() {
      $('.status .delete').click(function(e) {
        //Do something
      $('.status').dblclick(function(e) {
        //Do the same thing
    var bindingObject = {
      onReady : function() {
        $('.status .delete').click(bindingObject.deleteTweet);
      deleteTweet : function(e) {
        //Do something

10.3. Best Practices: Optimizing Selectors

  • Here are some tips to keep in mind when using selectors:
    • Id selections are really fast. They are handled by document.getElementById()
      // This is fast
      $('#statuses .status');
      //This is faster
    • Sizzle, the jQuery selector engine works bottom-up (right to left). Be more specific on the right side of your selector rather than on the left
      $('li.status .delete');
      $('.status img.delete');

10.4. jQuery Utility Methods

  • Most of the jQuery methods act on selections. Those methods are in the $.fn namespace (also called the jQuery prototype).
    • Receive and return the selection as this.
  • The other jQuery methods do not act on selections and are in the $ namespace.
    [Note] Note
    You need to be aware that in some cases, while these two namespaces might have the same method name, they are in fact different methods (for instance,$.fn.each to iterate over each selected element in a selection and $.each to iterate over an array or an object).
  • The utility methods that jQuery provides are very useful for doing routine programming tasks.
  • Here are some common jQuery utility methods. For more information, visit
    • $.trim(): This method removes leading and trailing whitespaces
      $.trim('    lots of extra whitespace    '); // 1
      1 Will return lots of extra whitespace
    • $.each(): This method iterates over objects and arrays
      $.each(['apple','banana','peach'], function(index, value) {
        console.log('index: ' + index + ' value: ' + value);
      $.each({ firstname : 'laurent', lastname : 'tonon' }, function(key, value) {
        console.log(key + ' : ' + value);
    • $.inArray(): This method checks if a value is contained in an array. If found it returns the value’s index of the array. Returns -1 if the value is not found
      var myArray = [ 23, 46, 31, 12 ];
      if ($.inArray(31, myArray) !== -1) { // 1
        console.log('found it!');
      1 This returns 2
    • $.extend(): This method merges the properties of the first passed object using the properties of the other passed objects as arguments. The first object is modified and returned by the method
      var myFirstObject = { fruit : 'apple', vegetable: 'carrot' };
      var mySecondObject = { fruit : 'banana' };
      var resultingObject = $.extend(myFirstObject, mySecondObject); // 1
      console.log(myFirstObject.fruit); // 2
      console.log(resultingObject.fruit); // 3
      1 Modifies the first object and returns the modified object
      2 3 Both print banana
  • jQuery also provides methods to determine the type of a variable ($.isFunction(),$.isPlainObject()$.isArray())

10.5. Avoiding Conflict With Other JavaScript Libraries

  • As we have seen, jQuery makes extensive use of the $ variable.
  • However, other JavaScript libraries like prototype make use of the $ variable sign as well, and might create conflicts.
  • Of course, you could use the jQuery variable instead (the $ variable is an alias to the jQuery variable) but it is obviously less convenient to type this in every instance.
  • The following examples are the same:
    //Using the $ variable
    //Using the jQuery variable
  • To avoid conflicts, you can put jQuery in no-conflict mode as soon as it is loaded in the page using the .noConflict() method:
    <script src="prototype.js"></script>
    <script src="jquery.js"></script>
    <script>var $j = jQuery.noConflict();</script> 1
    1 Create a new alias to jQuery$j

10.6. Queuing And Dequeuing Animations

  • Animations performed on an element are asynchronous.
  • Consider this example where we would have a <div> to animate:
    $('button').click(function () {
      $('div').animate({left:'+=200px'}, 2000);
      $('div').animate({top:'0px'}, 600);
      $('div').css('backgroundColor','red'); // 1
      $('div').animate({left:'10px', top:'30px'}, 700);
    1 One might guess that changing the background color would happen after the previous two animations have finished. However, this is not the case. The background would change almost at the same time as the first animations starts.
  • Each element has its own animation queue, fx (default queue), which is an array of functions.
  • Those queues are FIFO (First In First Out).
  • Using the following animation queue function, you are in total control of your animations:
    • You can add a function to the queue using .queue() (putting the function at the end of the stack)
    • Calling .dequeue() removes the top function from the stack and executes it
  • You could place your background changing operation on the fx stack like this:
    $('button').click(function () {
      $('div').animate({left:'+=200px'}, 2000);
      $('div').animate({top:'0px'}, 600);
      $('div').queue(function(){ // 1
        $(this).dequeue(); // 2
      $('div').animate({left:'10px', top:'30px'}, 700);
    1 Adds a function in the animation stack to be executed
    2 This allows the sequence of animation to continue. The next function in the queue is removed from the queue and then executed
  • You can get the animation queue of an element by calling .queue() on the matched selection. It would return an array of functions.
  • You could watch the state of the stack like this:
      $('span').html('Current Animation Queue Length for the div is ' + $('div').queue('fx').length);
    }, 100);

hackya 는

Attorney, front-end developer, digital media artist, WordPress enthusiast, & a father of 4 wonderful children.



Leave a Reply

Your email address will not be published. Required fields are marked *