mediumJS ES5#52

Module pattern (IIFE)

Prompt

Create a module using an IIFE that exposes a public API with add and getAll methods. The internal items array must be private, and getAll must return a copy so callers cannot mutate internal state.

Solution

var Store = (function() {
  var items = []
  return {
    add: function(item) { items.push(item) },
    getAll: function() { return items.slice() },
  }
})()
Mentor's take

Before ES modules existed, this pattern was the module system — every script shared one global scope, and an IIFE was how libraries like jQuery avoided leaking their internals into it. The function expression runs exactly once, creates a lexical environment holding items, and returns only the public API. The environment survives because the returned methods close over it; everything not returned is unreachable from outside — encapsulation enforced by scope, not documentation.

The detail that separates answers: getAll returns items.slice(), a defensive copy. Return the live array and every caller holds a write handle to your private state — Store.getAll().push(x) would corrupt the module from outside, silently defeating the whole point. Note the copy is shallow; if items were objects, callers could still mutate them — worth saying out loud.

The trade-off: singletons. The IIFE runs once, so there's exactly one Store — fine for app-level services, wrong when you need instances (that's the factory pattern from the closure-counter challenge). And ES modules give you this for free today with real static analysis; the IIFE remains interview-relevant because it proves you understand what the module syntax compiles down to.

Red flag: returning items directly from getAll. It reads as "I've never been bitten by shared mutable state."

Say it: "The IIFE runs once and its closure is the private scope — I return a slice so no caller ever holds a reference to internal state."