Module 6: Modern JavaScript, OOP, and Data
ES Modules: import and export
Split code into reusable files with explicit module boundaries.
ES modules let you divide a program into files with explicit exports and imports. They make dependencies visible and help avoid a single large script with many global variables.
A file named math.js might contain:
export function add(a, b) {
return a + b;
}
export const PI = Math.PI;
Another module imports named exports:
import { add, PI } from "./math.js";
console.log(add(2, 3), PI);
A module may also provide one default export:
export default function formatCurrency(value) {
return new Intl.NumberFormat("en-IN", {
style: "currency",
currency: "INR",
}).format(value);
}
Import it without braces using the name chosen by the importing file. Avoid mixing named and default exports unnecessarily; consistent conventions help teams.
Browser and Node.js differences#
Browsers can load modules with <script type="module">. Node.js supports ES modules, with configuration and file-extension rules depending on project setup. Follow the module system already used by a project rather than mixing CommonJS require with ESM imports casually.
Dependency direction#
Keep modules focused and avoid circular dependencies. Put shared, stable utilities in modules that do not import application features that depend on them.
Practice#
Split a tiny calculator into a math module and a separate entry-point file. Export two functions and import them explicitly.