Encapsulation means information hiding. It’s about hiding as much as possible of the object’s internal parts and exposing a minimal public interface.

The simplest and most elegant way to create encapsulation in JavaScript is using closures. A closure can be created as a function with private state. When creating many closures sharing the same private state, we create an object.

I’m going to build a few objects that can be useful in an application: Stack, Queue, Event Emitter, and Timer. All will be built using factory functions.

Let’s start.

Stack

Stack is a data structure with two principal operation: push for adding an element to the collection, and pop for removing the most recent element added. It adds and removes elements according to the Last In First Out (LIFO) principle.

Look at the next example:

let stack = Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop(); //3
stack.pop(); //2

Let’s implement the stack using a factory function.

function Stack(){
  let list = [];
  
  function push(value){ list.push(value); }
  function pop(){ return list.pop(); }
  
  return Object.freeze({
    push,
    pop
  });
}

The stack object has two public methods push() and pop(). The internal state can only be changed through these methods.

stack.list; //undefined

I can’t modify directly the internal state:

stack.list = 0;//Cannot add property list, object is not extensible

You can find more in the Discover Functional JavaScript book.

Discover Functional JavaScript was named one of the best new Functional Programming ebooks by BookAuthority!

For more on applying functional techniques to React take a look at Functional React.

Learn how to apply the Principles of Design Patterns.

You can find me on Medium and Twitter.