1. Home
  2. Javascript
  3. Object literal programming pattern

Object literal pattern, also known as modular pattern, is a way of organizing your javascript code. The biggest advantages of this approach is modularity, encapsulation and a clear, readable structure.

#javascript#object
// Declare an object
var Component = {

    // Set required variables here
    element : document.querySelector('.component'),

    // Add your methods
    componentMethod : function(){
        // Do something
    },

    // Initialization method
    init : function(){
        // Set the requirements that need to be met to execute the method
        if( Component.element ){
            this.componentMethod();
        }
    }

};

// Finally check for elements and initialize the object
if ( Component.element ){
    Component.init();
}
copy
Full Javascript cheatsheet