How to use modules in Javascript

Last updated : Sep 12, 2021

In this article you will get to know about the modules in Javascript

Javascript was programmed in 90s for providing basic dynamism to a wesbite for eg. wishing users in noon, evening or morning, form validation at client side and many other ways for making website interactive.

Javascript was just a normal scripting language which was used at a very minimal side. But with introduction of new standards by ECMA and Nodejs, Javascript has become the center point for the web development.

So now many large scale apps are also written in Javascript which needs repairs, maintainence and debugging time to time. For these tasks large scripts have to be separated in different files with code related to specific object or action. For eg. files we have in any framework are models, controllers, database, views etc.

In Javascript these separated files are called modules.

Enough of theory, it's time to implement these modules practically.

First of all let's see some ways in which modules can be scripted.

  • Expression style object.

    var Calculator = function(n1, n2){
        this.num1 = parseInt(n1);
        this.num2 = parseInt(n2);
    }
    
    Calculator.prototype.add = function(){
        return this.num1 + this.num2;
    }
    export default Calculator;
  • Function style object.

    function Calculator(n1,n2){
        this.num1 = parseInt(n1);
        this.num2 = parseInt(n2);
    }
    Calculator.add = function(){
        return this.num1 + this.num2;
    }
    export default Calculator;
  • Now very easy way for OOP programmer who have a habit of programming in C++ or Java.

    class Calculator {
        constructor(n1,n2){
            this.num1 = parseInt(n1);
            this.num2 = parseInt(n2);
        }
        
        add(){
            return this.num1 + this.num2;
        }
    }
    export default Calculator;

Let's create a basic calculator app through module in Javascript. While using a module in ES Javascript, always use it as a server most probably on a localhost. It will never run locally through a file in browser, it will always give a CORS error. Create a folder in server (if using XAMPP create your project directory in htdocs and in WAMP create your project drectory in www. Name it as app1.

  • Create a file named index.html for design and script it as follows:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Using module in JS</title>
        <style>
            input[type=text]{
                padding:5px;
                width:200px;
                font-size:20px;
            }
            .btn{
                width:100px;
                padding:10px;
                font-size:20px;
                font-weight: bold;
                background-color: orange;
                border:none;
            }
        </style>
    </head>
    <body>
        <div>
            <label>Enter num 1</label><br/>
            <input type="text" id="number_field_1" />
            
            <br/><br/>
    
            <label>Enter num 2</label><br/>
            <input type="text" id="number_field_2" />
            
            <br/><br/>
    
            <label>Answer</label><br/>
            <input type="text" readonly id="ans_field" />
            
            <br/><br/>
    
            <input type="submit" class="btn" value="+" id="add_btn" />
            <input type="submit" class="btn" value="-" id="sub_btn" />
            <input type="submit" class="btn" value="*" id="mul_btn" />
            <input type="submit" class="btn" value="/" id="div_btn" />
            <input type="submit" class="btn" value="Power" id="power_btn" />
        </div>
    
    
        <script type="module">
            import Calc from './modules/calc_module.js';
    
            var add_btn = document.getElementById('add_btn');
            add_btn.addEventListener('click',function(){
                var n1 = document.getElementById('number_field_1').value;
                var n2 = document.getElementById('number_field_2').value;
                var calc_tool = new Calc(n1,n2);
                document.getElementById('ans_field').value = calc_tool.add(); 
            });
    
            var div_btn = document.getElementById('div_btn');
            div_btn.addEventListener('click',function(){
                var n1 = document.getElementById('number_field_1').value;
                var n2 = document.getElementById('number_field_2').value;
                var calc_tool = new Calc(n1,n2);
                document.getElementById('ans_field').value = calc_tool.divide(); 
            });
    
            var sub_btn = document.getElementById('sub_btn');
            sub_btn.addEventListener('click',function(){
                var n1 = document.getElementById('number_field_1').value;
                var n2 = document.getElementById('number_field_2').value;
                var calc_tool = new Calc(n1,n2);
                document.getElementById('ans_field').value = calc_tool.subtract(); 
            });
    
            var mul_btn = document.getElementById('mul_btn');
            mul_btn.addEventListener('click',function(){
                var n1 = document.getElementById('number_field_1').value;
                var n2 = document.getElementById('number_field_2').value;
                var calc_tool = new Calc(n1,n2);
                document.getElementById('ans_field').value = calc_tool.multiply(); 
            });
            
            var power_btn = document.getElementById('power_btn');
            power_btn.addEventListener('click',function(){
                var n1 = document.getElementById('number_field_1').value;
                var n2 = document.getElementById('number_field_2').value;
                var calc_tool = new Calc(n1,n2);
                document.getElementById('ans_field').value = calc_tool.power(); 
            });
        </script>
    </body>
    </html>
  • Now create a directory named modules and on this directory create a file named calc_module.js and script it as follows:

    export default class Calc {
        constructor(n1,n2){
            this.num1 = parseInt(n1);
            this.num2 = parseInt(n2);
        }    
        add = function(){
            return this.num1 + this.num2;
        }
        subtract = function(){
            return this.num1 - this.num2;
        }
        multiply = function(){
            return this.num1 * this.num2;
        }
        divide = function(){
            if(this.num2 === 0){
                return "Cannot divide";
            }
            else{
                return this.num1 / this.num2;
            }
        }
        power = function(){
            var final_ans = 1;
            for(var i=1;i<=this.num2;i++){
                final_ans *= (this.num1);  
            }
            return final_ans;
        }
    }

Now you can test newly created app at http://localhost/app1 Done.



Sign in for comment. Sign in