I’d like to understand the jQuery plugin syntax

function(x){ 
    x...
}

is just a function without a name, that takes one argument, “x”, and does things with x.

Instead of ‘x’, which is a common variable name, you can use $, which is a less common variable name, but still legal.

function($){ 
    $...
}

I’ll put it in parentheses to make sure it parses as an expression:

(function($){
    $....
})

To call a function, you put () after it with a list of arguments. For example, if we wanted to call this function passing in 3 for the value of $ we would do this:

(function($){
    $...
})(3);

Just for kicks, let’s call this function and pass in jQuery as a variable:

(function($){
     $....
})(jQuery);

This creates a new function that takes one argument and then calls that function, passing in jQuery as the value.

WHY?

  • Because writing jQuery every time you want to do something with jQuery is tedious.

WHY NOT JUST WRITE $ = jQuery?

  • Because someone else might have defined $ to mean something else. This guarantees that any other meanings of $ are shadowed by this one.

Leave a Comment