javascript · level 3 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a file that shares only what it exports.
Real projects have hundreds of files. Each file is a module: its variables are private to that file, like the closures in unit 1. Writing before a function shares it, and another file writes to use it.
Gwecode runs one file at a time, so these lessons use a stand-in: an , a function wrapped in brackets and called the moment it is made. It runs once and returns what the module would export. Same idea: private inside, a few chosen names shared.
const tax = (() => {
const rate = 0.2;
function addVat(price) { return price + price * rate; }
return { addVat };
})();
console.log(tax.addVat(50));
console.log(tax.rate); In a real tax.js you would write export function addVat(price) { } and leave out the wrapper.
guess first
Two parts of an app use one module. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const counter = (() => {
let clicks = 0;
console.log("module loaded");
return { click() { clicks++; return clicks; } };
})();
const header = counter;
const footer = counter;
header.click();
console.log(footer.click());
your turn
Your turn. Export another function.
Add square to the names the module shares, then square a number of your choice. PI stays private.
fix it
The guest count is missing. Can you fix it?
countis written inside the module. Is it one of the names the module shares?- Only the names in the returned object are exported.
countstays private, soguests.countis undefined. - Change line 5 to
return { add, count };, then press run.
nailed it
your code has rooms with doors now. :D
- Each module keeps its own variables private.
exportshares a name;importbrings it in.- A module runs once, and everyone shares it.
new words in your collection
- module
- export
- import
- IIFE
This lesson isn’t saved. A free account remembers every lesson you finish.