Course contentsShow
← JavaScript
Lesson 515 of 2,72313. ClosuresFree lesson

Configuration Objects with Closures

Store configuration settings in closure scope and provide getters/setters for controlled access.

Configuration Objects with Closures

You'll learn how to use closures to encapsulate configuration settings and control access through dedicated getter and setter methods.

The Core Idea

Sometimes your functions need configuration—settings that control behavior but shouldn't be directly exposed. By storing configuration in a closure's scope, you create a "configuration object" that's private by default. You can then provide specific getter and setter functions to allow controlled access, preventing accidental or invalid modifications.

Think of it like a thermostat with a locked cover: the temperature settings are protected inside, but you can still read and adjust them using the buttons provided.

How It Works

The pattern captures configuration data in the outer function's scope. Inner functions returned from that scope can read and modify those settings, but external code cannot access the configuration directly—only through the functions you expose.

function createApp(initialConfig) {
  // Private configuration stored in closure
  let config = { ...initialConfig };

  return {
    getConfig(key) {
      return config[key];
    },
    setConfig(key, value) {
      // Can add validation here
      if (typeof value !== 'undefined') {
        config[key] = value;
      }
    },
    getAllConfig() {
      return { ...config }; // Return copy, not reference
    }
  };
}

const app = createApp({ theme: 'dark', lang: 'en' });
console.log(app.getConfig('theme')); // 'dark'
app.setConfig('theme', 'light');
console.log(app.getConfig('theme')); // 'light'
// config itself is inaccessible from outside

The configuration lives safely in closure scope. The returned methods act as gatekeepers, letting you add validation logic, prevent certain changes, or log access—all while keeping the actual data structure private.

Key Takeaway: Storing configuration in closure scope with getter/setter methods creates a controlled, private configuration system that protects settings from direct manipulation while still allowing necessary access.