Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all values of variable using JS

Tags:

javascript

So in my js code I have some global variable that changes its value several times, for example

var x = 0;
...
x = 10;
...
x = 5;

Is there any possibility to get "history" of x without saving its value in other variables? Like, is there some function to detect that at some point of time x was equal to 10?

like image 292
Coffee Avatar asked Dec 19 '22 10:12

Coffee


1 Answers

No, once a value is assigned to a variable, that variable's previous value is overwritten. It isn't retained anywhere. (If it were, it would be a nightmare for memory management.)

You could make an object property that retained a history if you wanted, by using a setter function; rough example:

var obj = {
  _fooValue: undefined,
  fooHistory: [],
  set foo(value) {
    this.fooHistory.push(this._fooValue);
    this._fooValue = value;
  },
  get foo() {
    return this._fooValue;
  }
};

obj.foo = 0;
obj.foo = 5;
obj.foo = 42;
console.log(obj.fooHistory);

In that example, the history doesn't contain the current value, just the previous ones, and it stores the current value in another object property which means code could bypass the setter. There are lots of tweaks you could do. If you thought it was important, you could lock it down more:

var obj = (function() {
  // These two vars are entirely private to the object
  var fooHistory = [];
  var fooValue;
  
  // The object we'll assign to `obj`
  return {
    set foo(value) {
      fooHistory.push(fooValue);
      fooValue = value;
    },
    get foo() {
      return fooValue;
    },
    get fooHistory() {
      // Being really defensive and returning
      // a copy
      return fooHistory.slice(0);
    }
  }
})();

obj.foo = 0;
obj.foo = 5;
obj.foo = 42;
console.log(obj.fooHistory);
like image 178
T.J. Crowder Avatar answered Dec 30 '22 08:12

T.J. Crowder