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 are a way to organize and reuse code by splitting it into separate files. Modules help developers encapsulate functionality, avoid polluting the global scope, and maintain clean and maintainable code.

Before ES6, JavaScript had no built-in module system. Developers relied on immediately invoked function expressions (IIFEs) or libraries like CommonJS and AMD. ES6 introduced native modules with import and export, which are now widely supported in modern browsers and Node.js.

1. What Are Modules?

A module is any JavaScript file that exports variables, functions, or classes so that other modules can import and use them.

  • Exporting: Make code available to other files.

  • Importing: Use code from another module.

Modules help in code reuse, separation of concerns, and maintainability.

2. Exporting in JavaScript

There are two types of exports: named exports and default exports.

Named Exports

Named exports allow multiple items to be exported from a module.

// mathUtils.js
export const pi = 3.14159;
export function add(a, b) {
  return a + b;
}
export function multiply(a, b) {
  return a * b;
}
  • Each exported item must be imported with the same name.

Default Export

A module can have one default export, which can be imported with any name:

// calculator.js
export default class Calculator {
  add(a, b) {
    return a + b;
  }
}
  • Default exports are useful when a module exports a single main functionality.

3. Importing Modules

Importing Named Exports

Use curly braces {} to import named exports:

// app.js
import { pi, add } from './mathUtils.js';

console.log(pi);      // 3.14159
console.log(add(5, 10)); // 15
  • The imported names must match the exported names.

Importing Default Exports

Default exports can be imported with any name:

// app.js
import Calculator from './calculator.js';

const calc = new Calculator();
console.log(calc.add(5, 10)); // 15
  • You can also combine default and named imports from a single module:

import Calculator, { pi, multiply } from './calculator.js';

4. Renaming Imports and Exports

Sometimes you want to rename imports to avoid conflicts:

import { add as sum } from './mathUtils.js';
console.log(sum(5, 10)); // 15
  • Similarly, exports can be renamed:

const subtract = (a, b) => a - b;
export { subtract as minus };

5. Dynamic Imports

ES2020 introduced dynamic imports using the import() function, which returns a promise.

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

loadModule();
  • Dynamic imports are useful for lazy-loading modules, improving performance.

6. Module Scope

Modules have their own scope, meaning variables declared inside a module are not added to the global scope:

// myModule.js
const secret = "hidden"; // Not accessible outside
export const visible = "public";
  • Only exported items can be accessed outside the module.

  • This prevents global namespace pollution, a common problem in large applications.

7. Re-exporting

You can re-export items from another module, making a central module for imports:

// utilities.js
export { add, multiply } from './mathUtils.js';
export { default as Calculator } from './calculator.js';
  • Consumers can import everything from utilities.js without worrying about individual modules.

8. Notes and Best Practices

  1. Use named exports when a module exports multiple functionalities.

  2. Use default exports when a module has a single main feature.

  3. Keep modules small and focused, following the single-responsibility principle.

  4. Use dynamic imports for lazy loading large modules.

  5. Organize modules in directories by feature to improve maintainability.

  6. Avoid polluting the global scope; rely on module encapsulation.

  7. Use consistent file extensions (.js) and module paths.

9. Summary of the Tutorial

  • Modules help in organizing JavaScript code into reusable, maintainable pieces.

  • Use export to expose variables, functions, or classes.

  • Use import to consume code from other modules.

  • Modules prevent global scope pollution and allow code separation.

  • Dynamic imports enable lazy-loading for performance.

  • Mastering modules is crucial for modern JavaScript development and framework usage.

Understanding JavaScript modules is key for scalable web development, as it promotes code reuse, maintainability, and performance optimization in real-world applications.


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.


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