Lesson 18 — Module pattern
Public API, private data
The module pattern uses a function that runs immediately (an IIFE — immediately invoked function expression, written (() => { … })()). Variables inside it are private; the object it returns is the public API — the only way to use them. Closures make the returned functions keep access to the private variables.
const bank = (() => {
let balance = 0; // private
return { deposit: (n) => (balance += n) };
})();
console.log(bank.balance); // undefined — hidden
Why it matters: hiding internals means nobody can break your data by accident — the same idea behind real modules and classes.
Add value() to the public API so the program prints 2, while counter.count stays undefined.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based JavaScript Intermediate courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for JavaScript Intermediate books — check the publication year so the examples match current versions.
Search Amazon →