Course contentsShow
← JavaScript
Lesson 673 of 2,72316. Object Methods and PatternsFree lesson

Returning Multiple Methods

Structure factories to return objects with multiple public methods that share private state.

Returning Multiple Methods

You'll learn how to build factory functions that return objects with multiple public methods, all sharing the same private data.


When you create a factory function, you're not limited to returning just one method. You can return an object containing as many methods as you need — and they all have access to the same private state through closure.

The Core Idea

Instead of returning a single function or a simple value, your factory returns an object literal with multiple methods. Each method is a function that can read and modify the private variables declared inside the factory. This gives you a clean way to expose several related operations while keeping internal data hidden.

How It Works

function createCounter(start) {
  let count = start; // Private state

  return {
    increment() {
      count++;
    },
    decrement() {
      count--;
    },
    getCount() {
      return count;
    }
  };
}

const counter = createCounter(10);
counter.increment();
counter.increment();
counter.decrement();
console.log(counter.getCount()); // 11
console.log(counter.count); // undefined — private!

Here, increment, decrement, and getCount all share access to the same count variable, but external code cannot access count directly.

Why This Matters

Returning multiple methods lets you build mini-modules or self-contained objects with a clean API. Each method can operate on the same private data, giving you controlled access without exposing internals. You define what the outside world can do, while keeping implementation details hidden.

Key Takeaway: Factory functions can return objects with multiple methods that all share access to private variables through closure, creating powerful, encapsulated modules.