tylermcginnis / javascriptvisualizer

A tool for visualizing Execution Context, Hoisting, Closures, and Scopes in JavaScript.

Home Page:https://tylermcginnis.com/javascript-visualizer/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Vars and closure not updating correctly on IIFE module code

tylermcginnis opened this issue · comments

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

console.log(counter.value()); // logs 0
counter.increment();
counter.increment();
console.log(counter.value()); // logs 2
counter.decrement();
console.log(counter.value()); // logs 1
var counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };
})();

counter.value();
counter.increment();
counter.increment();
counter.value();
counter.decrement();
counter.value();