JavaScript Modules: All the Stats, Facts, and Data You'll Ever Need to Know

Introduction to JavaScript Modules

As our application grows larger, it's essential to divide the code into several files, or "modules". A module can contain a class or a library of functions for a specific purpose. JavaScript didn’t have a language-level module system for a long time, but as scripts grew more complex, the community developed various module-loading systems.

Some examples of module systems:

What Is a Module?

A module is simply a file. Scripts can load one another, call functions, and exchange functionality using export and import directives.

Here's an example:

Example

mathModule.js (Module exporting functions):


// mathModule.js
export function add(a, b) {
    return a + b;
}

export function subtract(a, b) {
    return a - b;
}

    

app.js (Main script importing the module):


// app.js
import { add, subtract } from './mathModule.js';

console.log(add(5, 3)); // Output: 8
console.log(subtract(9, 4)); // Output: 5

    

Features of JavaScript Modules

1. Always “use strict”

Modules always operate in strict mode. For example, assigning to an undeclared variable in a module will throw an error, while regular scripts may not:

Example:


// mathModule.js
export function multiply(a, b) {
    result = a * b; // Error: 'result' is not declared
    return result;
}

    

2. Module-Specific Scope

Each module has a unique top-level scope, so variables and functions within a module are not visible to other scripts unless exported.


// user.js
let user = { name: "Harsh Kumar", role: "Blogger" }; // Not exported

    

3. One-Time Evaluation

Modules are only evaluated once. Importing the same module in multiple places will only execute its code the first time.

Example:


// logger.js
console.log("Logger module executed");

export function logMessage(message) {
    console.log(`Message: ${message}`);
}

    

// main.js
import { logMessage } from './logger.js';
logMessage("Main script is running"); // Output: Logger module executed

    

// helper.js
import { logMessage } from './logger.js';
logMessage("Helper script is running"); // Output: Message: Helper script is running

    

4. Meta Import

import.meta provides information about the current module, such as its URL.


// script.js
console.log(import.meta.url); // Outputs: https://example.com/scripts/script.js

    

Final Thoughts on JavaScript Modules

JavaScript modules divide functionality into distinct files, improving code organization and reusability. Modules enable the sharing of variables, functions, and classes between files using export and import. Even if a module is imported more than once, it is evaluated only once. Every module has its own scope and strict mode. import.meta contains information such as the URL of the module, which enhances performance, maintainability, and clean coding practices.

Published By: Meghna Batra
Updated at: 2024-09-26 20:41:26

Card Image

Ultimate Guide to Setting Up PHP Development Environment with Apache on Ubuntu 20.04

Comprehensive guide to setting up a PHP development environment using Apache on Ubuntu 20.04. Includes step-by-step instructions, installation of dependencies, SSL configuration, and setting up Laravel with Composer.

Card Image

Setup PHP Laravel Environment with Docker: Apache, Ubuntu, and MongoDB

Guide to setting up a PHP Laravel environment with Docker, including configuration for Apache, Ubuntu, and MongoDB.

Card Image

Setting Up CI/CD Pipeline for Laravel on GitLab with AWS EC2 Deployment

Guide to setting up a CI/CD pipeline for a Laravel project on GitLab, including deploying to an AWS EC2 instance and configuring SSH keys for remote access to a Git repository.

Card Image

Top 50 Docker Interview Questions and Answers

Prepare for your next DevOps interview with these top 50 Docker interview questions, designed to help you understand and master Docker's core concepts and practices.