JSFiddle - React, Tailwind, and code Playground

by moob

JavaScript

var something = function(){let k=0; return ()=>++k; }
var did = something();
console.log(did());
console.log(did());
console.log(did());


function counter() {
  var _counter = 0;
  // return an object with several functions that allow you
  // to modify the private _counter variable
  return {
    add: function(increment) { _counter += increment; },
    retrieve: function() { return 'The counter is currently at: ' + _counter; }
  }
}

// error if we try to access the private variable like below
// _counter;

// usage of our counter function
var b = counter();
var c = b;
c.add(5);  
var d = b; 
d.add(9); 

// now we can access the private variable in the following way
console.log(c.retrieve());
console.log(d.retrieve());
console.log(c.retrieve());