Skip to main content

Designing Modular JavaScript

    Closures, self-executing functions, immediately-invoked function expressions, and module patterns. Some of JavaScript's most advanced topics. At first glance, these can seem a little overwhelming but once understood they become as straightforward and repetitive as fundamental DOM manipulations.

    Coming from a Java background, learning JavaScript was a bit awkward. One might mistakenly suspect that JavaScript is just a bare form of Java. However, despite the names, there are more differences than similarities between the two languages. Java is a statically-typed, class based, object-oriented programming language. JavaScript is a dynamically-typed, prototype based, object-oriented programming language. Certain aspects of the syntax are the same (an if-statement is an if-statement), but the former differences are enough to create some headaches. Before I elaborate on some of JavaScript's more advanced topics, I'm going to break down the differences between Java and JavaScript, which will provide some insight and lead into the more advanced topics.

Static vs. Dynamic

    A statically-typed programming language (Java) means that the type of a variable is known at compile time. For instance:

    String name;
     Here, the variable name is defined as a String. It's value is known to be of type String and must remain as such otherwise an error will occur.

    A dynamically-typed programming language (JavaScript) is the opposite of a statically-typed language; the type of a variable is not known at compile time, instead, it is assigned at run time. For instance:

    var name;

    Here, the variable name is defined simply as a variable. It has no type until it is assigned a value at run time. Because of this, the type of the variable can change at anytime. So, name can be of type String by being assigned a String as a value, but if one's not careful, can be changed to a Number by then assigning its value a number.

Class vs. Prototype

    A common misconception is that JavaScript is not an object-oriented programming language. This is completely untrue. JavaScript is most certainly an object-oriented programming language and a prototypal one in that aspect. Since it's prototypal, it has a slightly different approach to it's object-oriented design compared to a class-based language. Without going too much in detail of all the nit-picky possible differences, I'll explain the most obvious of them.

    A class-based language (Java) can be seen as grouping an object and all its attributes and methods into a single file (you can put multiple classes into one file but let's focus on simplicity). This is a way of providing a clean and organized structure of data. Each object has its own class. An object can inherit properties from another by extending that objects class. Which would make the former object a subclass of the latter object. For example, pretend we have an object named Car, a subclass in Java would begin like:

    public class Sedan extends Car{}

    A prototype-based language (JavaScript) shares its attributes and methods through a "skeleton" like structure. This structure is a part of all objects of the same type and is how they inherit attributes. In JavaScript, all objects are descendants of Object and inherit from its prototype, Object.prototype. Therefore, all objects can be seen as linked or chained together. If one wants to change a method of an object and all its descendants, one would change the method in its prototype which would be inherited by all objects down the chain. For example, if we have an object named Car, a descendant would be defined like:

    Sedan.prototype = new Car();

And Car might be defined like so:

    var Car = function{/*attributes and methods*/}

    Both above code snippets could be declared in the same file. As you can see, there isn't as much of a visual organized structure in prototype-based languages, compared to class-based languages. However, this can be fixed which I will demonstrate in the following sections.

Self-Executing Functions

Finally! We made it to the "advanced topics". Well, here we go.

    In JavaScript, a self-executing function is a term to describe an anonymous function which is invoked  immediately after it is defined. For instance:

    (function{/*code and stuffs*/})();

    The above code snippet, is a very basic implementation of a self-executing function. It's anonymous (given no name). And it's invoked immediately after it's defined by the succeeding parentheses. The parentheses around the function are to allow it to parse as a expression (these are mandatory otherwise it won't be immediately invocable). And the following parentheses set, are to invoke the function (if you leave these out the function wouldn't be "self-executing" but can be defined for a variable which may later be invoked).

Immediately-Invoked Function Expressions (IIFE)

    An IIFE is arguably a better name for a self-executing function. And that's all it is. Simply a self-executing function as described above. 


    JavaScript contains no concept of classes. Also, it has no notion of private variables. We could organize objects or similar code into separate files and bring all these files into an HTML document via the script tag. This may make the code more readable but all objects defined will still be put into the Global Scope (numerous script files in an HTML document can be seen as one script file containing the code from all the others). This may lead to some name clashes if we're not careful. If only JavaScript had some way to define private variables to prevent name clashes between these files. Fortunately, there is an approach of imitating private variables with JavaScript. This approach is called closure.

    Closures are a somewhat complicated subject and sometimes require much thought and research to fully grasp the idea behind them. One answer to what a closure is that I like in particular is this one. It does a good job in breaking it down in a fun and easy fashion. Basically, in a shortened form, a closure is a method of using lexical scope (JavaScript) to simulate private variables. Here's how it works:

     Variables are within the Global Scope when defined outside functions. Variables defined inside functions are inaccessible after the function is done executing. Outside a function, you cannot access inner function attributes. Inside a function, you can access that functions attributes as well as all its parent functions (including global attributes). If you make a variable from within a function accessible outside the function (ex: by return it) it continues to have access to its original parent functions attributes, though, only it can access them. Which in turn, simulates private variables. For example:

    var outter = new Object(); //within the Global Scope
    function closureExample(){
        var inner = new Object(); //cannot be accessed outside function
        outter.someAttr = 5; //global/parent variables can be accessed within the function
        return function(){//function has access to parent function
            alert(JSON.stringify(inner));//access to parent functions attributes
    var test = closureExample();//returns the anonymous function
    test();//alerts with the value of a private variable, yet can't access variable directly

Module Pattern

    If we combined all our recently learned ideas (closure, IIFE, and the idea of separate file usage) we could create a system for writing dynamic JavaScript code while benefiting from patterns of a class based language. The module pattern does exactly that. The module pattern is a design pattern (way of writing and structuring code) that is independant of other code. Now, this may not be entirely true for it could still have dependencies but I believe its a much better way than just redundantly saying its modular. This pattern groups similar code into an IIFE (or in some circumstances it may not need to be immediately executed but the surrounding parentheses are still necessary) usually within its own file and revealing only certain attributes. For example:

              var privateVariable;
              function privateFunction(){}
                return {
                      publicVariable: 5,
                      publicFunction: function(){alert(privateVariable)}

Just ignore all my uncreative variable and functions names. Hopefully, it's good enough to get the idea across.

Revealing Module Pattern

    The revealing module pattern is almost identical to the module pattern except it names functions and variables it wants to reveal. It's just an arguable more clear and readable approach. For instance:

    //inside a module pattern
    var privateVariable = "Hey there!";
    var privateFunction = function(){alert(privateVariable)};

    return {
      sayHey: privateFunction

This article is a great read that provides more details on the module pattern.


    JavaScript is an amazing programming language. It has many advantages but also some disadvantages. These disadvantages have lead to the development of design patterns to fix these flaws and make it more efficient, such as, the module pattern.  With the understanding of these concepts one can design and develop large and efficient JavaScript applications. Hopefully, this article provides some insight into these subjects for someone. I know when I first started learning JavaScript it was a little awkward and such an article would have benefited me. If you find any errors or have anything to say feel free to leave a comment!


Popular posts from this blog

Face detection and live filters

Live video filters are becoming a popular trend fueled by Facebook (through their purchase of Msqrd) and Snapchat incorporating the features into their apps. These filters apply images or animations to your face using face tracking software. This technology has been around for awhile but is becoming increasingly more common due to the powerful CPU's that our mobile phones now have. Google provides an API that provides face tracking abilities through the Google Play Services library called Mobile Vision. I'm going to use their API to build a basic live filter app. The end result will look something like this:

    The bounding box wraps around the detected face and the sunglasses are the filter I chose (which is just a PNG image) which are drawn over the eyes. You could use any PNG image (with alpha for the background) you want, you will just have to adjust the layout according to where the image should be displayed. As you move your head, the box and sunglasses are redrawn…

Setting Up Connection Pooling With Elastic Beanstalk

Amazon's Elastic Beanstalk is a service which automatically scales your application when needed. It uses Amazon's Elastic Compute Cloud (EC2) instances as deployable containers which when your app requires more resources more containers will be deployed. This removes the need to manually configure your EC2 instance whenever you need more connections or resources and attempts to add simplicity to the maintenance aspect of your application. So, when you get more users of your app, your app will scale accordingly.

    Unfortunately, along with the ability to scale automatically, comes less control and configuration. Things you would normally have the ability to configure to your liking, such as your server, you no longer can. Amazon attempts to address this issue with configuration files. You can provide configuration files which can set up your server. These files are either written in JSON or the horrible format YAML. Though these files provide some level of control, you ca…

Android Guitar Tuner

Recently I created a guitar tuner application for Android that is written with pure Java (no C++ or NDK usage). The design was inspired by the Google Chrome team's guitar tuner web app using the WebAudio API. I wanted to code a version written natively for Android that didn't have to rely on a WebView, the WebAudio APIs, or server-side logic. Also, I wanted this application to be available to as many versions of Android as possible (whereas the WebAudio API may only be supported in more recent versions of WebView available only on newer flavors of Android). So, I coded it from scratch. I used a portion of the open source TarsosDSP project (their YIN algorithm) to help with the pitch detection.

    The application is available in the Google Play Store for Android: The project is completely open source and the code can be found on the GitHub repository: Fi…