Emulating private methods with closure

JavaScript do not provide a native way to achieve private method in other classical OO language,but it's possible to emulate it using closure because it provide a way to manage the global namespace.

var counter = (function() {  
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  return {
    increment: function() {
    decrement: function() {
    value: function() {
      return privateCounter;

console.log(counter.value()); // logs 0  
console.log(counter.value()); // logs 2  
console.log(counter.value()); // logs 1

The environment contains two private items: a variable called privateCounter and a function called changeBy. Neither of these private items can be accessed directly from outside the anonymous function. Instead, they must be accessed by the three public functions that are returned from the anonymous wrapper.Those three public functions are closures that share the same environment. Thanks to JavaScript's lexical scoping, they each have access to the privateCounter variable and changeBy function.