Loading...

Go Back

Next page
Go Back Course Outline

JavaScript Full Course


Modules in Javascript

Modules in JavaScript

1. What are Modules?

In JavaScript, modules are a way to organize and encapsulate code into reusable units. Each module typically represents a specific functionality or feature in your application. By using modules, you can keep your code organized, improve maintainability, and avoid polluting the global namespace.

Why use Modules?

  • Encapsulation: Modules help encapsulate functionality and avoid polluting the global scope.
  • Code Reusability: Once a module is created, it can be reused across multiple files or projects.
  • Separation of Concerns: Each module can focus on a specific part of the application, such as a service, utility function, or data processing logic.


2. CommonJS Modules (Node.js)

CommonJS is a standard used by Node.js to define how modules work. CommonJS modules allow you to export code from one file and import it into another.

Syntax:

  • Exporting: To export code from a module, you use module.exports.
  • Importing: To import code into another file, you use require().
                        
                        function add(a, b) {
                          return a + b;
                        }
                        
                        function subtract(a, b) {
                          return a - b;
                        }
                        
                        module.exports = {
                          add,
                          subtract
                        };
                            
                        
                        const math = require('./math'); // Import the math module
                        
                        const sum = math.add(5, 3);
                        const difference = math.subtract(5, 3);
                        
                        console.log('Sum:', sum); // Output: Sum: 8
                        console.log('Difference:', difference); // Output: Difference: 2
                            

Explanation: In math.js, we export the functions add and subtract by attaching them to module.exports. In app.js, we use require('./math') to import the math module and call its functions.

Output:

Sum: 8
Difference: 2

3. ES Modules (import/export Statements)

ES Modules (ECMAScript modules) are the modern standard for handling modules in JavaScript. ES modules are supported in modern browsers and JavaScript environments (like Node.js with proper configuration). They provide a more declarative approach to importing and exporting code.

Syntax:

  • Exporting: You can export variables, functions, or objects using export.
  • Importing: You can import the exported code using import.
                        
                        export function add(a, b) {
                          return a + b;
                        }
                        
                        export function subtract(a, b) {
                          return a - b;
                        }
                            
                        
                        import { add, subtract } from './math.mjs'; // Import functions from math.mjs
                        
                        const sum = add(5, 3);
                        const difference = subtract(5, 3);
                        
                        console.log('Sum:', sum); // Output: Sum: 8
                        console.log('Difference:', difference); // Output: Difference: 2
                            

Explanation: In math.mjs, we export the functions add and subtract using the export keyword. In app.mjs, we use the import keyword to import those functions.

Output:

Sum: 8
Difference: 2


4. Key Differences Between CommonJS and ES Modules

Feature CommonJS ES Modules
Syntax for Export module.exports = ... export and export default
Syntax for Import require('...') import ... from '...'
Dynamic Import No built-in dynamic import Supports dynamic import()
Module Loading Synchronously Synchronously or Asynchronously
Use Case Commonly used in Node.js Commonly used in browsers, modern JavaScript environments

5. Example of Using ES Modules in Node.js

To use ES Modules in Node.js, you need to use the .mjs file extension or specify "type": "module" in your package.json.

                        
                        export const add = (a, b) => a + b;
                        export const subtract = (a, b) => a - b;
                            
                        
                        import { add, subtract } from './math.mjs';
                        
                        console.log(add(3, 2)); // Output: 5
                        console.log(subtract(5, 2)); // Output: 3
                            

Explanation: In math.mjs, we export the functions add and subtract. In app.mjs, we import and use those functions.

Output:

5
3
Go Back

Next page