Module pattern

» Glossary » Module pattern

In JavaScript, it's known as Module pattern a technique by which we only expose the parts of our code that we are interested (the public API) through an object while we create a private state only accessible within the module:

var MyApp = (function( ){
    var public = {};
    var itemList = [];
    public.addItem = function( item ) {
        itemList.push( item );
    public.getItemList = function(){
        return itemList.splice(); // returns a new array
    return public;
})( );

The Module pattern is an evolution of the Namespace pattern – it actually can be seen as a factory to create a namespace using IIFEs. One fundamental difference is that the module has private state that may be shared and accessed by all the public methods it exposes – thanks to closures.

Recommended reading: