javascriptmodule-pattern

Does module pattern in javascript store variables?


const Formatter = (function() {
  let timesRun = 0;
  
  const log = (message) => console.log(`[${Date.now()}] Logger: ${message}`);
  const setTimesRun = () => {
    log("Setting times run");
    ++timesRun;
    console.log(timesRun);
  }

  const makeUppercase = (text) => {
    log("Making uppercase");
    setTimesRun();
    return text.toUpperCase();
  };

  return {
    makeUppercase,
    timesRun,
  }
})()

console.log(Formatter.makeUppercase("tomek"));
console.log(Formatter.timesRun);

console.log(Formatter.makeUppercase("foo"));
console.log(Formatter.timesRun);

console.log(Formatter.makeUppercase("hey"));
console.log(Formatter.timesRun);

With console.log(Formatter.timesRun); I'm expecting the incremented value of timesRun. However, it keeps logging 0. Using console.log(timesRun); inside the setRimesRun() function logs the incremented value. I don't understand where the data is stored and why am I getting 0.

I thought timesRun was always 0 and I added console.log(timesRun); to test it. It showed the incremeneted value which confused the me even more.


Solution

  • The variable timesRun is locally in the method setTimesRun. You should use the one outside of setTimesRun, so Formatter.timesRun.

    You can do like that:

    const Formatter = (function() {
      var timesRun = 0;
      const log = (message) => console.log(`[${Date.now()}] Logger: ${message}`);
      const setTimesRun = () => {
        Formatter.timesRun++;
        log("Setting times run to " + timesRun);
        //console.log(timesRun);
      }
    
      const makeUppercase = (text) => {
        log("Making uppercase");
        setTimesRun();
        return text.toUpperCase();
      };
    
      return {
        makeUppercase,
        timesRun,
      }
    })()
    
    console.log(Formatter.makeUppercase("tomek"));
    console.log(Formatter.timesRun);
    
    console.log(Formatter.makeUppercase("foo"));
    console.log(Formatter.timesRun);
    
    console.log(Formatter.makeUppercase("hey"));
    console.log(Formatter.timesRun);

    Here, all times I'm using the same variable: Formatter.timesRun. With this, all logger use the same and will some same instance of this int