Introduction
Modules help organize code by splitting it into smaller, reusable pieces. This makes programs easier to understand and maintain.
Modules help organize code by splitting it into smaller, reusable pieces. This makes programs easier to understand and maintain.
export function greet() { console.log('Hello!'); } import { greet } from './greet.js'; greet();
export to share code from a module.import to bring code from another module.// greet.js export function greet() { console.log('Hello!'); } // main.js import { greet } from './greet.js'; greet();
// math.js export const pi = 3.14; export function area(radius) { return pi * radius * radius; } // app.js import { pi, area } from './math.js'; console.log(area(2));
This program shows how to export a function from one file and import it in another to add two numbers.
// math.js export function add(a, b) { return a + b; } // main.js import { add } from './math.js'; console.log(add(5, 3));
Modules run in strict mode by default, which helps catch errors.
File paths in import statements usually need the file extension like .js.
Modules help avoid global variables that can cause bugs.
Modules split code into smaller, manageable parts.
They let you reuse and share code easily.
Modules keep code organized and prevent conflicts.
greet from a JavaScript module?export function functionName() {}.// file: math.js
export function add(a, b) { return a + b; }
// file: main.js
import { add } from './math.js';
console.log(add(3, 4));add is exported from math.js and imported correctly in main.js.add(3, 4) returns 3 + 4 = 7, which is logged.// file: utils.js
export function greet() { console.log('Hello'); }
// file: app.js
import greet from './utils.js';
greet();greet is exported as a named export, so import must use curly braces.Pass the test and this pattern moves unknown