Modules let you split code into separate files and share pieces between them.
export function add() {}: a named export.
export default class App {}: one default export per file.
import { add } from "./math.js";: import named exports.
import App from "./app.js";: import the default export.
In the browser, load the entry file with <script type="module" src="main.js"></script>. Module code runs in strict mode and has its own scope.
The example imports a real module from a CDN, since the editor has no separate files.
💡 Key Takeaways: JavaScript Modules
Mastering JavaScript Modules helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
JavaScript Modules Code Example
JavaScript
<pre id="out"></pre>
<script type="module">
// Import a function from a published ES module
import confetti from "https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/+esm";
const out = document.getElementById("out");
out.textContent = "Module loaded! Click the button.";
document.getElementById("party").addEventListener("click", () => {
confetti({ particleCount: 120, spread: 80 });
});
</script>
<button id="party">Celebrate 🎉</button>
Free sign-in required · Google login available
JavaScript Modules Practice Exercises
Check what you learned in “JavaScript Modules”.
/ 3 solved
Fill in the blank
Make the function available to other files.
function add(a, b) { return a + b; }
✓ Correct!Not quite. Try again.
Multiple choice
Which script type enables import/export in the browser?
✓ Correct!Not quite. Try again.
Code challenge
In a module script, set the text of #out to "Module works". (Use type="module".)
Write the code in the live editor. Your answer is checked automatically.