Private Collections
Private Collections
Closures can protect collection state by keeping the actual array inside an outer function. The public methods decide how the outside world can interact with that array.
Returning the private array directly breaks the boundary. A caller could mutate the returned array and change the store without using the store's methods. A safer getter returns a copy, preserving the closure as the only place where the real state can be changed.
Your task: Complete createTagStore. It should return an object with add(tag) and list() methods. add stores the tag and returns the current number of tags. list returns a copy of the stored tags, not the private array itself.
Free with a JS Exercises account
Sign in to start coding, run your solution, and keep your progress saved for later. No payment needed.
By continuing, you agree to our Terms and Privacy Policy. We'll send occasional product updates and news. You can unsubscribe anytime.
Private Collections
Closures can protect collection state by keeping the actual array inside an outer function. The public methods decide how the outside world can interact with that array.
Returning the private array directly breaks the boundary. A caller could mutate the returned array and change the store without using the store's methods. A safer getter returns a copy, preserving the closure as the only place where the real state can be changed.
Your task: Complete createTagStore. It should return an object with add(tag) and list() methods. add stores the tag and returns the current number of tags. list returns a copy of the stored tags, not the private array itself.