JS Modules
In this page:
export const name = value;
export default value;
import { name } from "./file.js";
import defaultName from "./file.js";
export and import Basics
export marks a function, variable, or class as available for other files to use, and import brings that exported item into a different file so it can be used there too.
उदाहरण: export and import Basics
// math.js
export function add(a, b) { return a + b; }
// main.js
import { add } from './math.js';
console.log(add(2, 3));
Default Exports
A default export represents the single main thing a module provides, and is imported without curly braces, using any name the importing file chooses.
A file can only have one default export, which is why it's typically used for a module's primary function, class, or component.
उदाहरण: Default Exports
// user.js
export default function createUser(name) { return { name }; }
// main.js
import createUser from './user.js';
console.log(createUser("Sam"));
Named Exports
Named exports let a single file export multiple distinct values, each imported individually by its exact exported name, wrapped in curly braces on the importing side. A module can freely mix multiple named exports alongside a single default export.
उदाहरण: Named Exports
// utils.js
export const PI = 3.14;
export function double(n) { return n * 2; }
// main.js
import { PI, double } from './utils.js';
console.log(PI, double(5));
Using type="module" in a Script Tag
Adding type=module to a script tag tells the browser to treat that script as an ES module, enabling import and export syntax, and automatically deferring the script until after the page has parsed.
उदाहरण: Using type="module" in a Script Tag
<script type="module">
// Import `{ add }` from the `./math.js` module
import { add } from './math.js';
// Print `add(1, 2)` to the console
console.log(add(1, 2));
</script>
Module Scope
Every module has its own private top-level scope, meaning variables and functions declared in one module file are not automatically visible in another, unless they're explicitly exported and imported.
उदाहरण: Module Scope
// counter.js
let count = 0; // private to this module, not visible elsewhere
export function increment() { return ++count; }
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS Dates
- JS Math
- JS Conditionals
- JS Switch
- JS Loop For
- JS Loop While
- JS Iterables
- JS Sets
- JS Maps
- JS typeof
- JS Type Conversion
- JS Destructuring
- JS Arrow Functions
- JS Classes
- JS Modules
- JS Promises
- JS Async/Await
- JS DOM
- JS DOM Methods
- JS Events Advanced
- JS DOM Navigation
- JS DOM Collections
- JS Async Callbacks
- JS Async Parallel
- JS Date Set
- JS Set Logic