How to add breakpoint on property change with JavaScript?

Sometimes, we want to add breakpoint on property change with JavaScript.

In this article, we’ll look at how to add breakpoint on property change with JavaScript.

How to add breakpoint on property change with JavaScript?

To add breakpoint on property change with JavaScript, we can define the property with a getter and setter.

Then we add debugger in the setter`.

For instance, we write

const obj = {
  someProp: 10,
};

obj._someProp = obj.someProp;

Object.defineProperty(obj, "someProp", {
  get() {
    return obj._someProp;
  },

  set(value) {
    debugger;
    obj._someProp = value;
  },
});

to call Object.defineProperty to add the someProp property to obj.

We add the getter with get and the setter with set.

We assigned the original someProp property to _someProp and we override the someProp property with the new one we just defined.

debugger is added to set to add a breakpoint when the value changes.

Conclusion

To add breakpoint on property change with JavaScript, we can define the property with a getter and setter.

Then we add debugger in the setter`.