BeginnerCoder

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.

Want it another way?
Task

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.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with JavaScript Intermediate

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.