How to write JavaScript Library
Programming #Javascript

So ever wondered writing own JavaScript library ? yes? so this post is for you. In this article I’ll show you some very simple way to start off writing own javascript library moreover the pattern of modularizing the code.

So lets start with some initial boilerplate.

var Demo = (function(){
    //All codes goes here...
    function init() {

    }

    //Returning revealed functions
    return {

    }
    init();//Invoking init()
})()

In this wrapper code we’re using Immediately Invoked Function Express (IIFE) which will contain our library functions and data. In a simple term the Immediately Invoked Function Express is invoking the function after initializing it. Here we can see that we’ve invoked the function using ( ) at the end of the function statement.

Initially the boiler plate has one function and one return statement. Since we’re using Revealing JavaScript Pattern that is why we have one return statement, so that we can only reveal functions that we want user to see not every functions.

While writing any library sometime we need to prepare data and some initial operations which are necessary. So its a good practice to use some init() function to initialize data and invoke function.

Lets create few more functions.

var Demo = (function(){
    var data = [];
    function init() {
        data.persons = [
            {name: 'John', age: 23},
            {name: 'Jaffery', age: 24},
        ]
    }
    function logPersons(){
        console.log(data.persons)
    }

    //Returning revealed functions
    return {
        logPersons: logPersons
    }
    //Invoking init()
    init();
})()

Now in init() function we have initialized few data. And the function logPersons() is just logging the data in the console.

Now if you want to access then you have only one function which is accessible logPersons() because we have returned that function.

Example

Demo.logPersons() //Returns data
Demo.init() //undefined
Demo.init() is undefined because its not revealed.

So this is the way to start off writing any js library. I hope this helps.

around a minute read 3rd Jul 2016

About

A entrepreneur, running an early stage venture, VizitDoc and a MVP-First Service Based Companay ThecodeWork.

A dreamer, having care for alternative education.

Archives - 1

  • Code

    20 Articles

    List of code snippet and articles I wrote when I started blogging in early 2016 😃

Codementor badge