JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Modules


JavaScript modules provide a way to organize and structure code by splitting it into reusable, self-contained files. Modules allow developers to import and export functionality such as variables, functions, classes, and objects across different files. This approach improves code maintainability, promotes reusability, and makes large applications easier to manage. With the introduction of ES6, JavaScript natively supports modules using export and import statements.

In this tutorial, you will learn about JavaScript modules, how to create and use them, practical examples, common mistakes, best practices, and real-world applications.

Why JavaScript Modules Are Important

Modules are important because they allow you to:

  • Break code into smaller, manageable files

  • Reuse code across multiple projects or files

  • Encapsulate functionality to prevent global scope pollution

  • Improve code readability and maintainability

  • Facilitate collaborative development in larger teams

Without modules, developers would need to include all code in a single file or rely on global variables, which can quickly become difficult to maintain and debug.

Creating Modules

A module is simply a JavaScript file that exports variables, functions, or classes so they can be used in other files.

Example: Exporting Variables and Functions

// student.js
export const name = "Aarushi";
export const age = 20;

export function greet() {
    console.log("Hello, my name is " + name);
}

In this example, the constants name and age, along with the function greet, are exported from the file student.js.

Exporting Multiple Items

You can export multiple items individually or together using named exports:

// utils.js
export const PI = 3.14159;

export function square(x) {
    return x * x;
}

export function cube(x) {
    return x * x * x;
}

Importing Modules

To use exported items from another file, you use the import statement.

Example: Named Imports

// main.js
import { name, greet } from "./student.js";

console.log(name); // Aarushi
greet();           // Hello, my name is Aarushi

Named imports must match the exported names exactly.

Importing Everything

You can import all exports from a module as a single object:

// main.js
import * as Student from "./student.js";

console.log(Student.name); // Aarushi
Student.greet();           // Hello, my name is Aarushi

Default Exports

Modules can have a default export, which allows importing without using curly braces.

// course.js
export default class Course {
    constructor(name) {
        this.name = name;
    }

    details() {
        console.log("Course: " + this.name);
    }
}

// main.js
import Course from "./course.js";

const jsCourse = new Course("JavaScript");
jsCourse.details(); // Course: JavaScript

A module can have only one default export, but multiple named exports.

Dynamic Imports

Dynamic imports allow you to load modules on demand, which can improve performance in large applications.

// main.js
async function loadCourseModule() {
    const module = await import("./course.js");
    const Course = module.default;
    const jsCourse = new Course("React");
    jsCourse.details();
}

loadCourseModule();

Dynamic imports return a promise and are useful for lazy loading or conditional module loading.

Common Mistakes

  • Forgetting to use relative paths when importing modules

  • Using curly braces with default exports incorrectly

  • Importing modules before they are properly exported

  • Mixing CommonJS (require) and ES6 modules (import/export)

  • Ignoring browser support and not using a bundler for older environments

Best Practices

  • Keep modules focused on a single responsibility

  • Use named exports for utility functions and constants

  • Use default exports for main functionality in a module

  • Organize modules logically in folders based on functionality

  • Use dynamic imports for performance optimization in large applications

Real-World Applications

  • Organizing utility functions, classes, and components in frontend frameworks like React or Vue

  • Creating reusable libraries for multiple projects

  • Structuring backend code in Node.js applications

  • Lazy loading modules in web applications to reduce initial load time

  • Encapsulating configuration and environment variables in separate files

Practical Examples

Example 1: Named Exports and Imports

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

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

// main.js
import { add, subtract } from "./mathUtils.js";

console.log(add(5, 3));      // 8
console.log(subtract(5, 3)); // 2

Example 2: Default Export

// user.js
export default class User {
    constructor(name) {
        this.name = name;
    }

    greet() {
        console.log("Hello, " + this.name);
    }
}

// main.js
import User from "./user.js";

const user = new User("Priya");
user.greet(); // Hello, Priya

Example 3: Dynamic Import

// main.js
async function loadModule() {
    const module = await import("./mathUtils.js");
    console.log(module.add(10, 5)); // 15
}

loadModule();

Example 4: Combining Named and Default Exports

// product.js
export const TAX_RATE = 0.1;

export default class Product {
    constructor(name, price) {
        this.name = name;
        this.price = price;
    }

    totalPrice() {
        return this.price + this.price * TAX_RATE;
    }
}

// main.js
import Product, { TAX_RATE } from "./product.js";

const phone = new Product("Phone", 500);
console.log(phone.totalPrice()); // 550
console.log(TAX_RATE);           // 0.1

Summary of JavaScript Modules

JavaScript modules enable developers to structure code into reusable, self-contained files. With export and import, you can share variables, functions, classes, and objects across files while maintaining modularity and preventing global scope pollution. Using default exports, named exports, and dynamic imports, developers can write scalable, maintainable, and performance-optimized applications. Following best practices ensures clean code organization, efficient code reuse, and easier debugging.


Practice Questions

  1. Basic Named Export and Import
    Create a module mathUtils.js that exports a function add(a, b) and a constant pi. Import them in another file and log their values.

  2. Default Export
    Create a module calculator.js with a default exported class Calculator that has an add() method. Import it in another file and create an instance to use the method.

  3. Combining Named and Default Imports
    Export a default class Calculator and a named function multiply from the same module. Import both in another file and use them.

  4. Renaming Imports
    Export a function subtract from a module and import it as minus in another file. Call the function to verify it works.

  5. Dynamic Import
    Use import() to dynamically load a module mathUtils.js and call an exported function add() asynchronously.

  6. Module Scope
    Create a variable in a module that is not exported, and another that is exported. Try accessing both from another file and observe which is accessible.

  7. Re-exporting Modules
    Create two modules mathUtils.js and calculator.js, then create a third module utilities.js that re-exports everything. Import everything from utilities.js in another file.

  8. Multiple Named Exports
    Export multiple functions (add, multiply, divide) from a single module. Import them individually and log their outputs.

  9. Default Export with Renaming
    Export a default class Person and import it with a different name in another file. Instantiate and use the class.

  10. Organizing Modules
    Create a folder structure with separate modules for math and string utilities. Import functions from both modules in a main file and use them together.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top