Modular JavaScript

This week we watched the first three videos in Modular JS by

Note: in the videos Will Stern refers to something called Mustache, it is not required that you understand what it is, it just simplifies his example. He also refers to Backbone. This video series was made before React became very popular, but Backbone is a framework that was a precursor to React. So, when you hear him say “Backbone”, just substitute it for “React” instead.

The videos concern the building of functions as so called “object literals” where a function is defined as an object instead and has a number of methods and variables assigned to it.

This is so that we don’t pollute the global namespace (define global variables) and only expose methods that can be accessed by other functions.

An example of a module is:

var personAndAge = (function(){

    var name = "Sara";
    var age = 37;

    // cache DOM
    var nameInput = document.getElementById("NameInput");
    var ageInput = document.getElementById("AgeInput");
    var addButton = document.getElementById("AddButton");

    // bind events
    addButton.addEventListener('click', addPersonAndAge, false);

    function render() {

        // render person and age


    function addPersonAndAge() {

        // add person and age


    return {

        addPersonAndAge: addPersonAndAge



Now the only exposed method is addPersonAndAge, even though we have other methods in our object literal, such as render.

Our code is also much cleaner and we have separated concerns, that is to say that we have split the code into methods that only handle what they are supposed to do.

This is quite similar to how ReactJS is built. If you get used to this style of building JavaScript, React syntax will not look so alien.

Leave a Reply

Your email address will not be published. Required fields are marked *