jQuery: variable scope and visibility

Variable scope is an important aspect of both JavaScript and jQuery coding. Scope hinges on the concept of variable visibility, that is, the fact that a variable is accessible within a given context or not. Since jQuery uses inline functions and closures very often, a proper understanding of how variables work turns out to be very useful in many possible scenarios.

Global variables

A variable is said to be global when it's accessible to all your jQuery code:


$(function() {

  var global = 100;
  
  $('#test').animate({
    left: global
  }, 'slow', function() {
  
    $(this).animate({
      left: - global
    }, 'slow');
  
  });

});

In this case, the variable global is accessible to all your jQuery code defined later. This happens because the variable has been defined at the very beginning of your code, just before any other jQuery routine. Its context is therefore global.

Local variables

The context of a local variable is accessible only to members of a particular jQuery code block. For example:

$(function() {

  $('#test li').each(function() {
  
    var local = 100;
    
    $(this).click(function() {
    
      $(this).animate({
        left: local
      }, 'slow');
    
    });
  
  
  });
  
  $('#test').animate({
    left: local
  });  // it doesn't work


});

In this case, the variable local is accessible only to the code defined within the each() construct, but not outside of it.

Beware of the var keyword

If you omit the var keyword when defining a variable, then your variable becomes part of the global window object. That is, if you forget to use this keyword, you're actually polluting the global namespace, and this can lead to unexpected and undesired results. So remember: always use the var keyword.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.