Jun 1, 2015

Syntax explanation of (function ($) { ..... })(jQuery)

A few months ago when I had to modify some JavaScript, I ran across code like the following that just baffled me in terms of the basic syntax.

    $(document).ready( ..... );

I'm now in a much better position to explain at the language level what's going on.

This explanation is not about jQuery nor about jQuery plugins, which a web search will show results for, such as the second article mentioned below.

Previously, I wrote that one of the ways to code the literal definition of a function is by using an expression that starts with the keyword function but does not include a name.

For example, this code defines an anonymous function and assigns it to a variable.

  var helloWorld = function() {
    console.log("hello, world");

The right-hand side of the = operator must be an expression that provides a value. In this case, it's a function object.

Likewise, here's a definition of another function object. The parentheses around it force it to be treated as an expression rather than as a regular function declaration.

  (function ($) {
    $(document).ready( ..... );

A single dollar sign $ is a valid identifier. So in this case, that's the name of the function's argument. That argument is apparently expected to be a function since $(document) looks like a call of $, whatever the actual argument is.

Let's add the final piece.

  (function ($) {
    $(document).ready( ..... );

The (jQuery) part of this expression means call the anonymously defined function, with jQuery as the actual argument.

In general, this kind of construct is known as an Immediately Invoked Function Expression (IIFE).

There's a slightly different way to write this code. I prefer the above, and it's what I've been seeing in practice. But the following is also correct.

  (function ($) {
    $(document).ready( ..... );


Immediately-Invoked Function Expression (IIFE)

What does (function($) {})(jQuery); mean?

No comments:

Post a Comment