Using the Immediately Invoked Function Expression

Immediately-Invoked Function Expression (IIFE)

The Immediately Invoked Function Expression (pronounced iify) is an excellent way to write modular namespaces in javascript.  This pattern is sometimes also know as  a Self Executing Anonymous Function, but that is not the terminology I will use here because it is slightly misleading since the function does not actually execute itself.

No matter what the documentation says, the source code is the ultimate truth, the best and most definitive and up-to-date documentation you’re likely to find.

-Jeff Atwood @CodingHorror

It’s very common for a new javascript developer  to throw every bit of javascript code they write into a few very large Javascript files (2000+ lines of code). It’s not uncommon for a single Javascript file to be 2000+ lines of code. I cry a little inside every time I have to open a javascript file like this. It’s painful to read and navigate, and personally I like my code to be self-navigating. I believe a semi-competent programmer should be able to follow my code without explanation.

Your code is a story, make sure it’s a story worth reading.

Global variables in Javascript are Evil.

If you didn’t know adding lots of variables to the global namespace is a very bad practice, now you know. Adding variables to the global namespace has the following negative effects:

      • You are polluting the global namespace with your code.
      • You are not utilizing basic programming concepts such as public/private functions.
      • It is possible that another developer will overwrite your variables/functions, creating bugs in  your code that are out of your control.
      • Your code will be very hard to read and understand as your codebase gets larger.

Introducing the Immediately-Invoked Function Expression (IIFE)

Pros

  • Gives you the ability to have public and private properties and methods
  • Allows your library to grow across files using the “window.namespace = window.namespace || {}” technique
  • A common pattern that you will see in many libraries, widgets, and plugins

Cons

  • Slightly more complicated pattern that might makes new javascript developers a little uncomfortable, because unless it doesn’t require the use of the new keyword.

There is a great pattern that addresses all of these problems . All it takes are some simple changes to how we structure our code.  Here is a code sample demonstrating  IIFE pattern to create a namespace called myNamespace. We’ll name this file MyNamespace.js

Let’s look at the example and then I’ll explain the code afterwards.

(function (myNamespace) {

} (myNamespace = window.myNamespace || {}));

The first time I saw this pattern I was very confused about what I was looking at, but we’ll start at the outside and work into the tougher concepts.

The opening parentheses cause Javascript to evaluate the code inside as a function expression.  Inside the opening parentheses we have an anonymous function that takes one parameter, our namespace object. The function is empty for now, but you’ll notice that immediately after the closing curly bracket  there is another set of parentheses with a variable be created and passed as a parameter to the function we just defined.

These parentheses are invoking the anonymous function immediately after the declaration. Inside the method invocation we check to see if the namespace already has been created in another file by checking the window object for our namespace myNamespace. If window.myNamespace is undefined, then an empty object is assigned to the myNamespace parameter that we are passing around. By doing this we can make sure that if the namespace exists then we only extend it, and if it has not been created then we create an empty namespace object.

Ok So Now What ?

We have a namespace.  Lets see how we can extend it :

(function (myNamespace) {

    //Private Variable
    var helloWorldMessage = "Hello Javascript";

    //Private Function
    var sayHi = function () {

        console.log(helloWorldMessage);

    };

    //Public Function
    myNamespace.helloWorld = function () {

        //call our private method
        //Prints "Hello Javascript" to the console
        sayHi();
    };

} (myNamespace = window.myNamespace || {}));

The IIFE pattern makes hiding functionality that shouldn’t change with private variable/functions easy, and exposes a nice public API for any consumer of this code. Now lets create another javascript file that extends this namespace to add some different functionality. Let’s call this file MyNamespaceExtension.js

(function (myNamespace) {

    //Private Variable
    var goodbyeMessage = "Goodbye Javascript";

    myNamespace.goodbyeJavascript = function () {

        console.log(goodbyeMessage);

    };

} (myNamespace = window.myNamespace || {}));

How Do I Use It ?

To use the namespaces we just defined we simply need a reference to the files and then we can instantly call them after they are loaded.

<html>

<head>

    <script src="../Scripts/MyNamespace.js" type="text/javascript"></script>

    <script src="../Scripts/MyNamespaceExtension.js" type="text/javascript"></script>

<script>

    myNamespace.helloWorld();

    myNamespace.goodbyeJavascript();

</script>

</head>

</html>

But I Need Nested Namespaces !

If you want to create a more complex namespace you can use the same creation pattern to create a new namespace within one of our modules.

(function (myNamespace) {

    //create a nested namespace
    myNamespace.nestedNamespace = myNamespace.nestedNamespace || {};

    //add a public function to our new namespace
    myNamespace.nestedNamespace.nestedMessage = function () {

        console.log("A clever message");
    };

} (myNamespace = window.myNamespace || {}));

And to call use the new namespace:

<html>

<head>

    <script src="../Scripts/MyNamespace.js" type="text/javascript"></script>

    <script src="../Scripts/MyNamespaceExtension.js" type="text/javascript"></script>

    <script src="../Scripts/MyNamespace.NestedNamespace.js" type="text/javascript"> </script>

<script>

    myNamespace.helloWorld();

    myNamespace.goodbyeJavascript();

    myNamespace.nestedNamespace.nestedMessage();

</script>

</head>

</html>

Summary:

      • We have severely reduced the footprint on the global namespace.
      • We have encapsulated functionality with a reliable pattern, exposing only a small subset of our code.
      • It is much less likely that your code will get stomped out by another developer.
      • It is now very easy to split our codebase up into separate files

Unit Testing with QUnit

Unit Testing Ajax Methods with QUnit

I took my first steps towards being a real javascript developer this past weekend. I began researching javascript testing frameworks with the intention of actually using one. I didn’t realize javascript had such a wide array of testing frameworks.

I was especially surprised to find out that some of the testing frameworks support TDD or BDD, but I digress. ..

This article is about using Qunit** to unit test http data requests. We’ll be getting some data from a REST service using Http Post.

For the sake of simplicity I will use jQuery’s ajax function for the sample code as I believe most javascript devevlopers are familiar with it’s usage.

My initial approach to get some data from a rest service had a couple inherent design flaws:

function getSomeData() {

$.ajax({

type: 'POST',

url: "../RestService/GetData",

success: function (data) {

//assign the data to a higher object property

myObj.myData = data;

},

dataType: "json"

});

};

 

When I looked at this from a testing perspective I discovered the following problems pretty quickly:

  1. To assert anything at all from a unit test we would have to explicitly create a dependency on an object (myObj) that has nothing to do with our test. All we want to do is validate the function got some data back. If myObj changed name, got added to a namesapce, or got deleted our test would fail for something that is out of our control.
  1. Qunit expects us to call stop() before initiating the asynchronous operation so that it can display the status of the asynchronous test in the Qunit results window and Start() when the async operation is complete. With the current setup we have no precise way of knowing when the success function is called. We could check the myObj.myData until it isn’t undefined, but I would rather throw my computer out the window than do that.

There are two patterns we can use to solve this problem I will talk about the pros and cons of both of them objectively and then give my personal opinion on which one I prefer.

Option 1: The Ajax complete pattern

The Ajax complete pattern is the when you return the XMLHttpRequest from an ajax post. Since we are using jQuery we will bind to the jqXHR object returned from the $.ajax() call. The jqHXR object is a superset of the browser’s native XMLHttpRequest object.  That let’s us easily bind to the done() event which fires upon a successful request (the name kind of implies that it will always fire but don’t be fooled).

To achieve this we must modify our getSomeData() method to return the result of the ajax call. Fortunately this is easily accomplished.

function getSomeData() {

return $.ajax({

type: 'POST',

url: "../RestService/GetData",

success: function (data) {

//assign the data to a higher object property

myObj.myData = data;

},

dataType: "json"

});

};

Now for the good stuff: The unit test.
We start by notifying QUnit  that this code is a test by wrapping it with the test() method.

The first parameter is the name of the test.

A good naming convention for tests is to be as specific as possible in regard to the unit of work currently under test.
We’ll name this test “Get Data with the ajax complete pattern”.

The second parameter is the test code wrapped in an Anonymous function.

test("Get Data with ajax.Done() pattern", function () {

//let QUnit know we are making an Asynchronous Test  call and are awaiting a response.

stop();

getSomeData().done(function (data, status, jqXHR) {

//let QUnit know that the Async test call is complete and test results are being gathered.

start();

//We are expecting 2 tests to pass.

expect(2);

//assert at least one series was returned

equal(data.length, 1, "At least one dataset was returned");

//assert that the series contains data

equal((data[0].someProperty.length &gt; 0), true, "At least one set of data returned");

});

});

The start() and stop() methods are used so that the QUnit testing results page can accurately display the status of an Async test.

Option 2: The callback pattern

This pattern requires a more drastic change to our getSomeData() function, but ultimately provides what I think is the better implementation.

We need to modify our getSomeData() function to accept a callback function as a parameter. Then we assign the function parameter to the value of the success callback function of the ajax request. It’s easier to understand if we look at the code changes.

function getSomeData(successCallback) {

$.ajax({

type: 'POST',

url: "../RestService/GetData",

success: successCallback,

dataType: "json"

});

};

Notice how we didn’t define a function for success ? We just passed in a callback object. Now we can have the calling code of this function work with the returned response dynamically. Many different charts, widgets, or any data driven component can now hook into this data call and manipulate the data in different ways.

What this also means is that our test can be a lot cleaner. We can write a callback function that includes the test and inspect the actual response of our Http call. In the previous test we assumed we were able to inspect the data by returning our jqHXR object. Our data call was restricted to working with the data one way. Using this call back pattern our data call is extremely reusable, which I hear is a good thing…

The second test display just how flexible this technique because the callback function we pass it includes our test assertions. I am a really big fan of this pattern.

test("Get Data with the callback pattern", function () {

//let QUnit know we are making an Asynchronous Test  call and are awaiting a response.

stop();

DataEntryPrototype.getSomeData(function (data) {

//let QUnit know that the Async test call is complete and test results are being gathered.

start();

//We are expecting 2 tests to pass.

expect(2);

//assert at least one series was returned

equal(data.length, 1, "At least one dataset was returned");

//assert that the series contains data

equal((data[0].someProperty.length &gt; 0), true, "Some distinct part of the of data was returned");

});

});

Both the solutions presented here accomplish the important goal  of asserting our data was returned. However the callback pattern is a really excellent example of how javascript can be powerful yet extremely concise and elegant.

** if you are not familiar with QUnit syntax at all check out this article: how-to-test-your-javascript-code-with-qunit

HTML5 & CSS3 Polyfills

Browser degradation is the most crucial problem we face when enjoying all the cool features in HTML5 and CSS3. Thanks to the work of some really talented and smart developers we are able to fix the holes in these browsers using polyfills. 

What is a polyfill ?

polyfill: A shim that mimics a future API, providing fallback functionality to older browsers.

Using Polyfills in combination with the Mordernizr javascript library enables us to have a finite level of control over how our css renders.

To start off here is a link to Paul Irish’s amazing polyfill resources list:

https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills

And here is Modernizer

http://www.modernizr.com/

These two links are the most comprehensive approachs to regressive enhancement I have found.

I also just heard that Modernizr will be shipped with ASP.NET MVC 3 Tools along with jQuery !