JavaScript Modules

Modules help organize JavaScript code by splitting it into reusable files using export and import keywords.

Why Use Modules?

  • Keep code organized and maintainable
  • Reuse functions or variables across files
  • Separate logic into logical units

Exporting from a Module

Create a file named math.js:


// Named export
export function add(a, b) {
  return a + b;
}

export const PI = 3.14;

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

Importing a Module

In your main file (e.g., app.js):


// Named imports
import { add, PI } from "./math.js";

// Default import
import subtract from "./math.js";

console.log(add(5, 3));     // 8
console.log(subtract(9, 4)); // 5
console.log(PI);             // 3.14
            

Notes

  • Use type="module" in your HTML script tag:

<script type="module" src="app.js"></script>
            
  • Modules run in strict mode by default
  • File paths must include .js

Practice Task

Create a utils.js module with a function greet(name) that returns "Hello, <name>". Import it and display the greeting in your main file.