Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Modularity in JavaScript

In this article we will discuss about the modularity approach in java script programming.

Modularity helps the process of organizing the entire code base. So if modular approach is not applied then the structure will grow and become out of control. The modular approach in javascript programming helps to develop more structured code and make it easily maintainable.

Introduction

In modular programming approach, we follow two things when make the structure of the application:

  • Separate different functionalities into smaller part which forms the module.
  • Make the relation between the modules.

It is obvious that the modules will have dependency. This dependency is maintained through function call (with passing variables) among the modules. And it works only when the modules are loaded.

But during making the dependency structure, we must ensure that circular dependency is not formed. In case of circular dependency modules are not loaded properly (if module X and Y depends on each other, which one should load first?). Each module will wait for the other module to get loaded. So in this type of situation the dependency is not straight forward and the application fails. The developer should always take special care during design phase of the modules.

Back ground

If we check the most modern programming languages then we will find that it has the modular system inbuilt. But in case of java script, the inbuilt availability of modular support is not available. So it is the responsibility of the developer to take the modular approach. The best way to do this is to put every module in a separate file and then load that java script file in a proper order. This approach makes it clear which module is in which file and the related things should be kept in a single place.

Java Script loading

Java script loading is an important aspect of the modular design approach. Java scripts are kept in a file with (.js) extension and it is used within a tag in a html file. Now the browser loads the java script file when it finds <script> tag with a 'src' attribute on the web page. There is also a different approach to load a java script file from console. The load () function is used to load the java script file. Following is a sample code for loading java script file from console.

Listing1: Sample code to load a java script file


load("sample.js");

As we have seen in the previous section that load command is useful to load java script files from console. But we should be careful about the sequence of loading files. Because if some dependency is involved among java script files then the order of loading is of great concern. If one file is dependent on a second file but that is not loaded yet then it will be unable to find the constructor and show errors. One way to solve the issue is to put load calls at the top of the file for a module. It will load all the files first before they are required. But there is always a dependency on the browser side. So calling load function does not mean to load the file immediately. Rather the execution of the current file will complete first and then the second file will be loaded. Sometime this mechanism gets delayed and cause problem.

So the practical approach is to manage dependency manually by hand. Use the <script> tag inside html file and load the java script file. And manage the order inside the html file. So the browser will check the html file and load java scripts according to the order mentioned in the html.

Dependency Management: So we can understand that dependency management is an important aspect for java script file loading. There are mainly two ways to automate dependency management. But this approach manages dependency partially.

The first approach is to create a separate file with details about the dependencies among modules. After this the file is loaded first and then determines the order to load other files. Following is a sample dependency file. The file contains the dependent java script files.

Listing2: Sample code to load dependent java scripts

var dependencyobj =
  {"TestOne.js": ["TestTwo.js"],
   "TestThree.js":  ["TestOne.js"],
   "TestFour.js":  ["TestTwo.js", "TestThree.js"]};

The 'dependencyobj' contains a property for each file and describes the dependency among java script files. It is more likely a key-value pair type of design where the values of the mentioned properties are arrays of java script file names.

The dependency manager is responsible for two vital tasks to make this approach successful. First, it should make sure that java script files are loading in correct order. It ensures the dependency loading before it is accessed. Secondly, no files should be loaded twice or more. Otherwise it will cause errors and loss of performance.

The following sample is showing the loading of files. The required function is used to load files and its dependencies. The recursive call loads all the java script files and its dependencies.

Listing3: Sample code to load a java script file recursively

var loadedJSFiles = {};

function require(Jsfile) {
  if (dependencyobj[Jsfile]) {
    var Jsfiles = dependencyobj[Jsfile];
    for (var i = 0; i < Jsfiles.length; i++)
      require(Jsfiles[i]);
  }
  if (!loadedJSFiles[Jsfile]) {
    loadedJSFiles[Jsfile] = true;
    load(Jsfile);
  }
}

In the second approach, do not use any <script> tag within the html file. Instead use 'eval' function to execute the content as a java script code. This approach loads scripts instantly and therefore easy to use. The 'eval' is an interesting java script function. The full name is 'evaluate'. The function takes string as an argument and executes it as a java script code. The following code shows the sample code to execute the eval function.

So the power of eval function can be used to perform some interesting tasks in java script. The function can build new code and execute it. So if there is a need to pass some function as variable and the user does not know it in advance, eval can be used to execute the code at run time by passing it to the eval function. Sometime eval function creates some confusion during execution time.

All new variables are treated as local when eval is called inside a function. So the local variables will be lost when the function returns. So when we use eval, care should be taken to prevent this situation.

eval("print(\"Printing string input\");");

Another important aspect is where the top level java script variables are stored. As the browser loads java script file, all top level variables are placed in a single place called 'window' object. This 'window' is used along with the object to access these variables. The method can be used by calling show function with an argument like 'show (window);'

Let us take a complete example of module in java script:

Listing4: Sample showing the implementation of module in java script

function newMonthNameMod() {
  var monthnames = ["Jan", "Feb", "Mar", "Apr",
               "May", "Jun", "Jul", "Aug", "Sept",
               "Oct", "Nov", "Dec"];
  function getMonName(nbr) {
    return monthnames[nbr];
  }
  function getMonNbr(name) {
    for (var nbr = 0; nbr < monthnames.length; nbr++) {
      if (monthnames[nbr] == name)
        return nbr;
    }
  }

  window.getMonName = getMonName;
  window.getMonNbr = getMonNbr;
}
newMonthNameMod();

show(getMonName(7));

This sample module is showing translation of month and their number. Different functions are called to show the month name by passing the number as the argument.

Conclusion

To conclude the discussion we can say that there is lot of tool kits available which covers the basic java script requirements. So either you have to follow one of the tool kit to develop application specific java script library or make something from scratch. But for developing fresh library requires a lot of coding effort. So the best approach is to follow one standard tool kit and customize it using modular approach as described above.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login