JavaScript Functions

There is much to be said about JavaScript?s functions and many different ways in which they can be created. A function is also a JavaScript object (of type Function.) Functions are unique in that they are both an object and a function. A String object, for example, does not have the ability to execute JavaScript statements like a function. Yet, both String and Function are objects.

Functions are very common in JavaScript programming. It’s one of the first things you get to learn after variables and for-loops. Most people probably just use the following format to create and call a JavaScript function.

    // Function definition
    function myFunc() { /* code here */ }

    // Execute (call) the function

Everybody knows that this is how functions work.
But there is more than one way to create a function:

    // Standard function definition
    function myFunc1() { ... }  

    // As an assignment to an anonymous function
    var myFunc2 = function() { ... };  

    // Using the function object
    var myFunc3 = new Function("...");

Where the dots ? stand for the statements the function will execute. Also known as the function body. Notice that in the third case we are using the Function object to create the function, the body of the function is entered as a string and passed to the first parameter.

We can call either one of the functions we just defined as follows:

    myFunc3(); // Function created using new operator whose body is defined as a string

In JavaScript you can create any type of an object using the new operator. For example to create a new string: new String(?abc?); or a new array new Array(1,2,3); In the end these statements evaluate to exactly the same thing as var str = ?abc?; or var arr = [1,2,3]; The syntax is the only thing that is different. Because we know that (almost) everything in JavaScript is an object whichever way we create it, all of this applies to functions (which are objects, too) as well.

Anonymous Function

An anonymous (nameless or unnamed) function can be created using the syntax below:

    function() { ... }

In event-based programs anonymous functions are often passed as arguments to event listeners. In this case they are referred to as callback functions:

    $(?div#button?).on(?click?, function() { ? });

Here, the anonymous function is the callback function for the click event occurring on div#button element. This means that whatever is placed within { ? } will be executed when the event is finished executing. In other words when the event is finished processing completely.

This technique is very common and in particular popular when using together with Ajax events (which create HTTP requests to retrieve contents of a web page or a script.) Ajax requests can take time to finish. For example, the page you are requesting may be hosted on a slow server, of it simply takes time for it to finish processing the request. The anonymous function waits until Ajax request completes fully.

The program may not have a way of knowing when such an Ajax event will finish doing its work. Therefore it is wise to execute any code that is assumed to work with the results of that Ajax call… within the callback function itself, instead of trying to process it as soon as the Ajax statement is executed (which is a common mistake.) The data may not be even available yet at this time.

Using Anonymous Functions to Provide Scope for variables

One of the most confusing function constructs in JavaScript is the following:

Example 1

    ( function() { ? } )();

So what in the world is going on here? We know that anonymous functions don?t have a name by design. But simply writing function() { alert(?hello?) } does not evaluate to a JavaScript statement that will execute. We simply created an anonymous function object. And we can never use it because there is no name handle on it.

However, wrapping the anonymous function with parenthesis gives us the ability to execute it soon after it is defined. This way we can create a nameless function and execute it without having to use a name (which doesn’t exist in the first place.)

In order to understand why anyone would want to do such a thing, we need to talk about JavaScript variable scope.

Unlike C++ and Java, in JavaScript variables are scoped to functions and not blocks delimited by the brackets { }. In other words:

var x = 1;


…is a completely valid JavaScript statement. But both alert boxes will display the real value of x which is 1. The variable x is stored in global scope of the program. Other languages do not allow this. The value x would not be visible within { } brackets. Only local variable x would be available there, if it existed.

But a function changes that. Anything specified in any function (anonymous or not) becomes scoped to the brackets within that function. Let?s take a look:

Notice that I am using typeof function instead of just alert(b). Whenever JavaScript encounters a variable that is not defined within that scope, the entire program will come to a halt and stop executing at that line of code. typeof checks the type of a variable, but if the variable doesn’t exist it will not break the flow of execution.

    // define var b inside function:
    var g = function() { var b = "boom"; alert(typeof(b)); };
    ( g )(); // will display ?string? because that is the type of variable b

    alert(typeof(b)); // not accessible here, returns ?undefined?

    // Again type of b is undefined,
    // because the variable is confined to the scope of the original function
    function h() { alert(typeof(b)); }
    h(); // displays ?undefined?

From this we can determine that the variable b is only available for access from within the first function, the one that defined it, but not in global scope.

And back to the original statement:

    (function(){ ? })();

Notice that we created an anonymous function and by wrapping it in parenthesis we are giving it the ability to refer to itself from the very statement it is defined in. Now that we can do that, we can execute the function we just created using the parenthesis operator (); This operator can be used to execute any function, anonymous or not:

// Define some functions
var x = function() { ? };
function y() { ? };

// Execute functions using () operator:

So we create an execute an anonymous function on the same line. All variables created within it will be constricted to its body and not available from the global scope of the application.

This technique in particular is popular when creating jQuery plugins. Why? Because plugins are stand-alone pieces of software that are designed to be used from a ?foreign? application written by someone else. What if that someone else decided to name some of their variables the same names that you named variables in your code? The anonymous function hides the names of those variables within its scope. This means there will never be a conflict created between your plugin and the variables defined by the website it is being used on.

Using Functions to Bind and Unbind events

Another appropriate place in your code for using a function is when it comes to creating and listening to events. Let?s first create a function that will execute when a click event is registered on an element:

    var function = doSomething() { ? };

    // Attach event
    $(?div?).on(?click?, doSomething);

    // At some point later in your program, stop listening to click event:
    $(?div?).off(?click?, doSomething);

jQuery Tutorials