monitor variable change in javascript

How to Listen to Variable Changes in JavaScript

Generally, we attach event handlers to DOM elements in case we need to monitor them for changes. But sometimes you may want to listen to variable changes in JavaScript. This is especially true if you want to keep an eye on certain important variables that you don’t want to unexpectedly change. In this article, we will learn how to listen to variable changes in JavaScript.


How to Listen to Variable Changes in JavaScript

JavaScript allows you to monitor changes made to an object using Proxy objects. Proxy objects allow you to create a copy of an object that can be used in place of the original object but also allows you to intercept & redefine getting, setting and

Here is a simple example to monitor changes to a given variable.

var targetObj = {};
var targetProxy = new Proxy(targetObj, {
  set: function (target, key, value) {
      console.log(`${key} set to ${value}`);
      target[key] = value;
      return true;
  }
});

targetProxy.hello_world = "new"; // console: 'hello_world set to new'

In the above code, Proxy object allows you to override set function for the object which is triggered whenever you change the value of object, thereby displaying a message.

You can also do the same thing using accessors. Each object property supports accessors which are basically functions that allow you to get/set value of the said property. You can use them to redefine the behavior of getting/setting property value. In the following object aInternal stands for x.a’s value.

x = {
  aInternal: 10,
  aListener: function(val) {},
  set a(val) {
    this.aInternal = val;
    this.aListener(val);
  },
  get a() {
    return this.aInternal;
  },
  registerListener: function(listener) {
    this.aListener = listener;
  }
}

Once you have defined the get and set functions for x.a, you can register the listener using the following code.

x.registerListener(function(val) {
  alert("Value of x.a changed to " + val);
});

So when you change the value of x.a by simply using assignment operator, it will display the above mentioned alert.

x.a = 21;

In this article, we have learnt how to listen to variable changes in JavaScript.

Also read:

How to Reset Primary Sequence in PostgreSQL
How to Pass Parameter to SetTimeout Callback
How to Generate Random String in JavaScript
How to Fix PostgreSQL Error Fatal Role Does Not Exist
How to Install Python Package Using Script

2 thoughts on “How to Listen to Variable Changes in JavaScript

  1. Hi. Nice option to monitoring change in object attibs. One coment, i thinj you have a mistake in this line “a.x = 21;”.I think must be x.a = 21;

Leave a Reply

Your email address will not be published. Required fields are marked *