JavaScript Modules
Published by Brayan K
A JavaScript module is a self-contained file that exposes its code to other files using export and pulls in code from elsewhere using import, keeping each part of an app organized and reusable.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Run real modules before discussing build tools
This editor has one code pane. To keep the examples complete and offline, each module is supplied as a small data URL containing JavaScript source. import() passes that source to the runtime’s real ES module loader and returns a promise for its namespace. There is no simulated module cache or replacement import function. In a project, these source strings normally become separate files.
const source = "export function double(value) { return value * 2; }";
const moduleURL = "data:text/javascript," + encodeURIComponent(source); // Embed source safely.
const numbers = await import(moduleURL); // The runtime parses and evaluates a real module.
console.log(typeof numbers.double);
console.log(numbers.double(4));
// ✅ Expected output:
// function
// 8The outer await observes the dynamic import. The export keyword belongs to the loaded module source, not to the editor’s outer function. data URLs are an exercise delivery format, not a recommendation for organizing a production app. The examples print values, never encoded source URLs or machine-specific paths.
Match named and default exports deliberately
const asModule = source => "data:text/javascript," + encodeURIComponent(source);
const library = asModule('export const unit = "kg"; export default function format(value) { return value + " kg"; }');
const consumer = asModule(
"import show, { unit as label } from " + JSON.stringify(library) + ";" +
'console.log(show(3)); console.log(label);'
);
await import(consumer);
// ✅ Expected output:
// 3 kg
// kgInside the consumer, show is an arbitrary local name for the default export. unit names a particular named export, and as label chooses its local name. The braces in a static import are import syntax; they are not object destructuring executed at runtime.
const asModule = source => "data:text/javascript," + encodeURIComponent(source);
const library = asModule("export const count = 2;");
const consumer = asModule(
"import { missing } from " + JSON.stringify(library) + ";" +
'console.log("consumer ran");'
);
try { await import(consumer); }
catch (error) { console.log(error.name); }
// ✅ Expected output:
// SyntaxErrorThe consumer asks for an export the library does not provide. Linking fails with SyntaxError before its console.log executes. Full diagnostics contain a module identifier and differ across hosts, so this caught fixture checks the actual error name instead. A default import also requires a default export; named and default are not interchangeable guesses.
Live bindings are not copied values
const asModule = source => "data:text/javascript," + encodeURIComponent(source);
const counter = asModule("export let count = 0; export function increment() { count++; }");
const consumer = asModule(
"import { count, increment } from " + JSON.stringify(counter) + ";" +
"console.log(count); increment(); console.log(count);"
);
await import(consumer);
// ✅ Expected output:
// 0
// 1const url = "data:text/javascript," + encodeURIComponent(
"export let count = 0; export function increment() { count++; }"
);
const namespace = await import(url);
const { count } = namespace;
namespace.increment();
console.log(count, namespace.count);
// ✅ Expected output:
// 0 1Static import creates a live binding. In contrast, const followed by object destructuring reads a namespace property at that moment and initializes an ordinary local variable. Destructuring Assignment owns the general destructuring rules.
const asModule = source => "data:text/javascript," + encodeURIComponent(source);
const library = asModule("export let count = 0; export const options = { compact: false };");
const consumer = asModule(
"import { count, options } from " + JSON.stringify(library) + ";" +
'try { count = 9; } catch (error) { console.log(error.name); }' +
'options.compact = true; console.log(count, options.compact);'
);
await import(consumer);
console.log((await import(library)).options.compact);
// ✅ Expected output:
// TypeError
// 0 true
// trueRead-only binding does not mean deeply frozen data. The assignment to count fails, while mutating the shared options object succeeds. Export functions or factories when callers should use a controlled interface rather than share mutable objects.
const asModule = source => "data:text/javascript," + encodeURIComponent(source);
const expression = await import(asModule(
"let value = 1; export default value; export function change() { value = 2; }"
));
const binding = await import(asModule(
"let value = 1; export { value as default }; export function change() { value = 2; }"
));
expression.change();
binding.change();
console.log(expression.default, binding.default);
// ✅ Expected output:
// 1 2export default value evaluates an expression for the default export. export followed by a binding list can instead export the existing value binding under the name default. This distinction matters when that local binding is reassigned.
Module scope and caching have observable consequences
const module = await import("data:text/javascript," + encodeURIComponent(
"const hiddenModuleValue = 7; export const value = hiddenModuleValue; export const top = this;"
));
console.log(module.value, typeof hiddenModuleValue, module.top);
console.log(Object.hasOwn(module, "hiddenModuleValue"));
// ✅ Expected output:
// 7 undefined undefined
// falseModules run in strict mode. Their private top-level names do not become variables in the importing module or properties on the global object. That is organization and encapsulation; code you import still executes with the capabilities of its environment, so importing untrusted code is not a security boundary.
await import("data:text/javascript," + encodeURIComponent(
"unownedModuleBinding = 3;"
));
// ✅ Expected error:
// ReferenceError: unownedModuleBinding is not definedconst url = "data:text/javascript," + encodeURIComponent(
'console.log("module evaluated"); export let count = 0; export function add() { count++; }'
);
const first = await import(url);
const second = await import(url);
first.add();
console.log(first === second, second.count);
// ✅ Expected output:
// module evaluated
// true 1Within this run, the same resolved module URL identifies the same module instance. Importing it again does not reset its state or repeat its top-level side effect. Each new editor Run starts a fresh execution environment, so this example begins cleanly again. Prefer an exported factory for independent instances rather than changing URLs to force repeated loading.
const source = "export function createCounter() { let count = 0; return () => ++count; }";
const { createCounter } = await import("data:text/javascript," + encodeURIComponent(source));
const first = createCounter();
const second = createCounter();
console.log(first(), first(), second());
// ✅ Expected output:
// 1 2 1The module is shared, while each factory call creates separate closure state. Closures and Scope owns that state model; JavaScript Design Patterns (Factory, Singleton, Strategy, etc.) owns choosing factories and shared services.
Static imports, dynamic imports and paths solve different problems
try {
new Function('import { value } from "data:text/javascript,export const value=1";');
} catch (error) {
console.log(error.name);
}
console.log((await import("data:text/javascript,export const value=1")).value);
// ✅ Expected output:
// SyntaxError
// 1A static import declaration belongs at module top level and uses a string-literal specifier. import(expression) is an expression that returns a promise and can be used conditionally or inside a function. Both use the module loader. Dynamic import does not automatically prove a bundler produced a separate downloadable chunk.
In a browser project, load an entry file through a script element with type="module" and serve it over HTTP with an appropriate JavaScript MIME type. Relative imports are resolved from the importing module’s URL, not from the page’s visual location. A bare name such as "library" needs a host-specific resolution mechanism, such as a browser import map, a package resolver or a bundler. Native Node and browser resolution are not identical.
The embedded data modules here have no directory for resolving "./helper.js", so dependency examples supply complete data URLs. They do not test a server’s MIME type, cross-origin permission or deployment paths. Module Bundlers: Webpack, Parcel, Vite (Overview) owns bundler configuration and tree shaking; Deploying JavaScript Apps (CDN, Minification, Bundling) owns published asset delivery.
Initialization order still matters
await import("data:text/javascript," + encodeURIComponent(
"console.log(total); const total = 4;"
));
// ✅ Expected error:
// ReferenceError: Cannot access 'total' before initializationThis direct example fails before total is initialized. Cyclic imports are not automatically forbidden, but a cycle can expose a similar early read of an imported lexical binding. Keep module dependencies understandable and move shared contracts into a dependency both sides can use; Writing Maintainable & Scalable Code Architecture owns dependency boundaries and larger application structure.
Guided exercise: expose only the intended interface
Fill the literal hints to export a named function, load its module and call it through the namespace. The quoted source is real module code when import loads it.
const source = "___ function triple(value) { return value * 3; }"; // 👉 replace ___ with export
const module = await ___("data:text/javascript," + encodeURIComponent(source)); // 👉 replace ___ with import
console.log(module.___(4)); // 👉 replace ___ with triple
// ✅ Expected output:
// 12Independent brief: separate a cart factory from its consumer
Write a module exporting createCart and no shared cart instance. Each cart has add(name), names() and size(). add requires a non-empty trimmed string, stores the trimmed name and returns the new count; invalid names throw TypeError("name must be a non-empty string"). names returns a new array so callers cannot mutate internal membership. Duplicate names are allowed. A separate consumer module must statically import the factory, create two carts, and prove their independence and the copy boundary.
Keep parsing and state in the library, and printed examples in the consumer. Check two additions, duplicates, whitespace trimming, a modified returned array, a second empty cart, and invalid values. Use complete embedded modules in this editor; the same exported source can be placed in a separate project file.
const asModule = source => "data:text/javascript," + encodeURIComponent(source);
const librarySource = `export function createCart() {
const items = [];
return {
add(name) {
if (typeof name !== "string" || name.trim() === "") {
throw new TypeError("name must be a non-empty string");
}
items.push(name.trim());
return items.length;
},
names() { return items.slice(); },
size() { return items.length; }
};
}
`;
const libraryURL = asModule(librarySource);
const consumerSource = "import { createCart } from " + JSON.stringify(libraryURL) + ";" + `
const first = createCart();
const second = createCart();
console.log(first.add(" pear "), first.add("apple"), first.add("pear"));
const view = first.names();
view.push("outside");
console.log(first.names().join(","), first.size(), second.size());
console.log(first.names() === first.names());
for (const invalid of ["", " ", null, 3]) {
try { first.add(invalid); }
catch (error) { console.log(error.name, error.message); }
}
console.log(first.size(), second.size());
`;
await import(asModule(consumerSource));
const namespace = await import(libraryURL);
console.log(Object.keys(namespace).join(","));
// ✅ Expected output:
// 1 2 3
// pear,apple,pear 3 0
// false
// TypeError name must be a non-empty string
// TypeError name must be a non-empty string
// TypeError name must be a non-empty string
// TypeError name must be a non-empty string
// 3 0
// createCartReference notes
The import reference specifies live read-only bindings and module-only static declarations. The JavaScript modules guide covers module loading and scope. Node’s data import documentation explains why embedded modules cannot resolve relative file paths.
Practice quiz
What does this complete program print? const m = await import("data:text/javascript,export const value=4"); console.log(m.value);
- 4
- undefined
- Promise
- value
Answer: 4. The imported namespace exposes the declared named export.
What does this complete program print? const url = "data:text/javascript,export let value=1;export function change(){value=2}"; const m = await import(url); const {value} = m; m.change(); console.log(value,m.value);
- 2 2
- 1 2
- 1 1
- 2 1
Answer: 1 2. Ordinary destructuring captures the current value; reading the namespace sees the updated binding.
What does this complete program print? const url = "data:text/javascript,export const value=3"; console.log((await import(url)) === (await import(url)));
- false
- undefined
- true
- 3
Answer: true. The same module identity reuses its namespace in this run.
What does this complete program print? const m = await import("data:text/javascript,const secret=5;export default secret"); console.log(m.default,typeof secret);
- 5 number
- undefined number
- undefined undefined
- 5 undefined
Answer: 5 undefined. The default export is available, while the unexported module binding is out of scope.
What does this complete program print? const m = await import("data:text/javascript,export const top=this"); console.log(m.top);
- undefined
- globalThis
- null
- TypeError
Answer: undefined. Module top-level this is undefined.
What does this complete program print? const m = await import("data:text/javascript,export default function(){return 7}"); console.log(m.default());
- default
- 7
- undefined
- TypeError
Answer: 7. The namespace property default contains the exported function.
What does this complete program print? const m = await import("data:text/javascript,export const settings={compact:false}"); m.settings.compact=true; console.log(m.settings.compact);
- false
- TypeError
- true
- undefined
Answer: true. Read-only export bindings do not deeply freeze an exported object.
What does this complete program print? const m = await import("data:text/javascript,export function make(){let n=0;return ()=>++n}"); const a=m.make(),b=m.make(); console.log(a(),a(),b());
- 1 2 3
- 1 1 1
- 2 2 2
- 1 2 1
Answer: 1 2 1. Each factory call creates a separate closure even though the factory comes from one module.
Continue this course
- Previous: Async/Await Architecture & Best Practices
- Next: Prototype Chain & Advanced OOP Patterns — Traverse the prototype chain and build mixins and composable objects
- Quick reference: JavaScript cheat sheet