Functions are used extensively in jQuery and they have the same form as that of JavaScript. Functions are a useful programming language construct since they allow code-reuse. If there is a piece of code/task that is needed at multiple places in the program, then we can write it in a single function and merely call it from multiple places. jQuery also uses functions popularly to create callback handlers for various events; more on events a little later!
In JavaScript, functions belong to the category of objects. However, if we were to use the typeof operator against a function name, then it would return "function" instead of "object".
There are two important properties of functions: arguments and returns values. Arguments are a set of variables that a caller can pass to a function. A function can take any number of arguments (including none!) and uses these arguments as an input to its logic. If the caller passes extra arguments than what is specified in the function definition, then JavaScript silently ignores them! On the other hand, if the caller passes less number of arguments, then JavaScript sets the missing arguments as undefined. Fairly flexible!
A return value is a value that the function passes back to the caller. This value is, typically, based on the argument input and function uses these argument to compute the return value. Having said that, it is not necessary for a function to return any value!
Besides arguments and return values, a function definition also has several additional syntax elements. First, we need to provide "function" keyword to identify that the object is indeed a function. Second, we need to provide the name of the function; however, this step is optional and we can write functions with no names as well! Third, we need to provide zero or more arguments. Fourth, we should enclose the body of the function within curly braces ({}). Last, if needed, a function can also return a value.
With that, let us see an example that implements functions. The code provided below implements a function ("funcNobelLaureateAuthor") which takes the name of a book as an input and returns the name of the author. To do so, it uses an object to hold book/author pairs and returns the name of the author for the passed book. Since functions are objects, the example also uses another variant where it assigns the function directly to a variable and then uses that variable to invoke the function! When we run the example, it would print "Rabindranath Tagore" and "G. B. Shaw".
<!doctype html> <html> <div id="idDiv"></div> <script type="text/javascript"> // Get a handle of the div element. var elem = document.getElementById("idDiv"); // Define an object to store books/author pairs. var objNobel = {"Pygmalion": "G. B. Shaw", "Gitanjali": "Rabindranath Tagore"}; // First implementation: define a simple function. function funcNobelLaureateAuthor(book) { return objNobel[book]; } // Invoke the function using its name. retStringDoes = funcNobelLaureateAuthor("Gitanjali"); elem.innerHTML += retStringDoes; // Prints "Rabindranath Tagore". // Second implementation: define a function and store it as a variable. var varFunc = function (book) { return objNobel[book]; }; // Invoke the function using the variable. elem.innerHTML += varFunc("Pygmalion"); // Prints "G. B. Shaw". </script> </html>
Now, JavaScript functions can also be anonymous (with no names), so it is possible to define the function and invoke it then and there! In fact, anonymous functions are used very commonly in both JavaScript and jQuery.
To illustrate this, let us rewrite our earlier example such that we make the funcNobelLaureateAuthor() function an anonymous function and invoke it right away. Once we have defined the anonymous function, we provide an argument within a pair of parenthesis ( as "("Gitanjali")") at the end to indicate that we would like to invoke the function immediately. If we run this example, it would print "Rabindranath Tagore".
<!doctype html> <html> <div id="idDiv"></div> <script type="text/javascript"> // Get a handle of the div element. var elem = document.getElementById("idDiv"); // Define an object to store name/action pairs for books/authors! var objNobel = {"Pygmalion": "G. B. Shaw", "Gitanjali": "Rabindranath Tagore"}; // Invoke the function anonymously. elem.innerHTML += function funcNobelLaureateAuthor(book) { return objNobel[book]; }("Gitanjali"); // Prints "Rabindranath Tagore". </script> </html>