TalentJR

🟨 JavaScript tutorial for beginners · Class 9 · Lesson 11 of 18 · Free

ES6 Modules – Split JavaScript into Files with import and export

⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Export functions and values from one file and import them into another
  • Choose between named exports and a default export, and rename imports with as
  • Load a module in a web page and load one later, only when needed, with import()

Your quiz app has grown to 600 lines in one file. Finding the scoring code takes ages, and when your friend edits the same file, things break. Real apps split code into small files, each with one job, like chapters in a textbook. JavaScript modules are how those files share code with import and export.

Why split JavaScript code into modules?

A module is just a JavaScript file that shares some of its code with export. Another file takes that code with import.

Each file has one job: marks.js for calculations, quiz.js for questions, main.js to start the app. Small files are easier to read, test and share with friends.

The boxes on this page have tabs: 📄 main.js and the other files. They run here as real modules, exactly like in a real project. Open the marks.js tab to see what it exports.

🟨 JavaScript — you can edit this code
Console output
Average: 68
Pass

💡 Only what has export in front can be imported. Everything else in marks.js stays private to that file.

How do export and import work in JavaScript?

Put export in front of a const or function to share it. In the other file, write import { name1, name2 } from "./file.js". The names in { } must match the exported names exactly.

The path starts with ./ ("this folder") and ends with .js. Browsers need both.

After the import, PASS_MARK and average are used like any normal value and function. Watch the animation: main.js runs line by line, calling average from the other file.

📄 marks.js
export const PASS_MARK = 33;
export function average(list) {
  const sum = list.reduce((a, b) => a + b, 0);
  return Math.round(sum / list.length);
}
🎬 How JavaScript thinks — step 1 of 9JavaScript is about to run line 1
▶import { PASS_MARK, average } from "./marks.js";
2
3const results = { Asha: [72, 45, 88], Kabir: [20, 31, 40] };
4for (const [name, marks] of Object.entries(results)) {
5 const avg = average(marks);
6 console.log(name, avg, avg >= PASS_MARK ? "Pass" : "Fail");
7}
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Asha 68 Pass
Kabir 30 Fail

💡 Try it: add export const MAX = 100; in marks.js, import MAX too, and print it.

What is a default export in JavaScript, and when do I use { }?

A file can also have ONE default export: its main thing. You import it WITHOUT { } and can give it any name you like.

Named exports: import { LANG } from "./greet.js" (exact name, with braces). Default export: import greet from "./greet.js" (any name, no braces).

One line can import both: the default first, then the named ones in braces.

🟨 JavaScript — you can edit this code
Console output
Namaste, Ishaan!
Language: Hindi

💡 The function is called greet inside greet.js, but main.js names it sayHello. For a default export, the name is your choice.

How do I rename an import or import everything with * as?

Two files may both export a function called format. Rename one while importing: import { format as formatMoney } from "./money.js".

import * as marks from "./marks.js" puts every named export into one object called marks. Then you write marks.average(...) and marks.PASS_MARK. This is called a namespace import.

You can also rename while exporting: write the functions first, then export { rupees as format } at the end of the file.

🟨 JavaScript — you can edit this code
Console output
₹250.00
26/1/2027
85 33

💡 Without as, both imports would be called format, and JavaScript would stop with an error.

What is different about code inside a JavaScript module?

Module code always runs in strict mode. Using a variable without let or const is an error, not a silent new global.

Each module has its own scope. Its top-level variables are not shared with other files unless exported. At the top level, this is undefined.

A module runs only ONCE, however many files import it. Below, team1.js and team2.js both import score.js, yet "score.js is running" prints once, and both share the same runs.

🟨 JavaScript — you can edit this code
Console output
score.js is running
Total: 10
this at top level: undefined

💡 Files can import each other: main.js → team1.js → score.js. Total is 10 because both teams use the one shared score.js.

How do I load a module only when it is needed (dynamic import)?

import … from must be at the top of a file and loads before your code runs. But await import("./quiz.js") can be called anywhere, for example inside a click handler.

This makes pages start faster: heavy code (a game, a chart) loads only when the user asks for it.

Click Start quiz twice. The file runs the first time; the second time it is already loaded and does not run again.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Page ready. quiz.js is not loaded yet.

💡 In a web page you load main.js with <script type="module" src="./main.js"></script>. Plain <script> without type="module" cannot use import.

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

📄 counter.js
let count = 0;
export function next() {
  count++;
  return count;
}
📄 main.js
import { next } from "./counter.js";
import * as again from "./counter.js";

next();
next();
console.log(again.next());

Question 2. main.js runs as a module. What does it print?

console.log(typeof this);

Question 3. What does this print?

📄 hi.js
export default function hi() {
  return "Hi";
}
export const name = "Asha";
📄 main.js
import * as m from "./hi.js";
console.log(m.default(), m.name, m.hi);

🧩 Your challenge

grades.js is ready (open its tab). It has a NAMED export grade(marks) and a DEFAULT export reportLine(name, marks). Write main.js: import both in one line, print a report line for each student, and count how many got "A". Expected output: Asha: 92 (A) Rohan: 78 (B) Meera: 33 (C) Kabir: 20 (Needs help) A grades: 1

Expected output in the console:
Asha: 92 (A)
Rohan: 78 (B)
Meera: 33 (C)
Kabir: 20 (Needs help)
A grades: 1
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

import * as math from "./math.js";
console.log(math.add(2, 3));

TypeError: math.add is not a function

✅ Right

import * as math from "./math.js";
console.log(math.add(2, 3));

Without export, a function stays private to its file. Other files cannot see it, so math.add does not exist.

❌ Wrong

import { greet } from "./greet.js";
console.log(greet("Asha"));

SyntaxError: The requested module './greet.js' does not provide an export named 'greet'

✅ Right

import greet from "./greet.js";
console.log(greet("Asha"));

A default export is not a named export, so { greet } finds nothing. Import a default WITHOUT braces: import greet from "./greet.js".

❌ Wrong

import { average } from "./marks";
console.log(average([90, 80]));

TypeError: Cannot find module "./marks" — the files here are: marks.js

✅ Right

import { average } from "./marks.js";
console.log(average([90, 80]));

In the browser the path must be the exact file name, with ./ and the .js ending. "./marks" is a different (missing) file.

📌 Remember

  • A module is a JavaScript file that shares code with export and uses other files' code with import.
  • Named exports: import { a, b } from "./file.js" — names must match.
  • One default export per file: import anyName from "./file.js" — no braces.
  • Rename with as, or import everything into one object with import * as name.
  • Modules run in strict mode, have their own scope, and run only once however often they are imported.
  • Use <script type="module"> in HTML, and await import() to load code only when needed.

Finished the quiz and the challenge?

Questions students ask

What are ES6 modules in JavaScript?

ES6 modules are the built-in way to split JavaScript into separate files. A file shares functions or values with export, and another file uses them with import. All modern browsers and Node.js support them.

Why do I get a CORS error when I open my module page from a file?

Browsers do not load modules from file:// pages for safety. Run a small local web server instead, for example the Live Server extension in VS Code, and open the page through http://localhost.

What is the difference between export default and export?

A file can have many named exports but only one default export. Named exports are imported with braces and their exact names. The default export is imported without braces and you choose its name.

Do I need modules for small projects?

Not always. For a tiny page, one file is fine. Once your project has several parts, like a quiz, a score board and helpers, modules keep it tidy and make teamwork much easier.