JS Tutorial



JS MODULES


JavaScript Modules 📦

JavaScript modules allow you to break your code into smaller, reusable pieces. This improves maintainability, readability, and debugging. With modules, you can import and export code across different files.

🔄 Exporting from a Module

To share code from one file (module), use the export keyword:

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

🔄 Importing into Another Module

To use code from another module, use the import keyword:

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

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

📦 Default Exports

For a single export from a module, you can use the default export:

// math.js
export default function multiply(a, b) {
  return a * b;
}

Then, import it like this:

// app.js
import multiply from './math.js';

console.log(multiply(2, 3)); // 6

🎮 Interactive Example

Click to see how modules work in a simplified setup:

📘 Summary

  • Export: Use export to expose functions or variables from a module.
  • Import: Use import to bring in functions or variables from another module.
  • Default Export: Use export default when exporting a single item from a module.
Tip: Modules work best with a build tool or server, but modern browsers support type="module" for client-side JavaScript.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review