Challenge - Modular structure
Build a counter module with private state using ES modules and closures.
Counter module
In this challenge you will build a counter module with private state. Only increment and read access are exposed; the count itself cannot be reached directly.
You use a closure for this. The createCounter function defines let count = 0 inside and returns increment and getCount methods.
Finally you export the function from the module with export default createCounter. Other files can import and use it.
Private state with closures
A closure is when an inner function reaches the outer function's variables. When createCounter is called a fresh count is created and only the returned methods can see it.
You cannot write counter.count from outside, because count is not a property of the object but a variable of the closure.
This technique is the basis of the module pattern: the public API is open, the inner state stays hidden.
Exercise Write the createCounter function
Write the createCounter() function. Inside it declare let count = 0. Return an object with increment and getCount methods: increment increases the counter by one, getCount returns the current value. End with the export default createCounter line.
Show example solution
function() { count = count + 1; }, getCount: function() { return count; } }. End the last line with export default createCounter;.
Example solution:
function createCounter() {
let count = 0;
return {
increment: function() { count = count + 1; },
getCount: function() { return count; }
};
}
export default createCounter;
Test yourself
-
How do you write a default export in an ES module?
- export default createCounter
- module.exports = createCounter
- exports.createCounter
- public createCounter
Show answer
export default createCounter — Correct. export default ships one default value from the module.
-
Write the default export
export ____;Show answer
export default createCounter;