Skip to content

Instantly share code, notes, and snippets.

@ajitid
Last active May 18, 2026 14:45
Show Gist options
  • Select an option

  • Save ajitid/3419660444dc1639f7c932f693cb2247 to your computer and use it in GitHub Desktop.

Select an option

Save ajitid/3419660444dc1639f7c932f693cb2247 to your computer and use it in GitHub Desktop.
observing when a value changes in JavaScript

Here we've put a breakpoint when the value on globalThis.store.aamras.banana[0].chameli[2].dhatura. If we open the DevTools console and run this and then change the dhatura's value, it will trigger a breakpoint.

1. via a setter

  (() => {
    const prefs =
      globalThis.store?.aamras?.banana?.[0]?.chameli;
    const pref = prefs?.[2];
    if (!pref) return console.warn("pref [2] not there yet");
    let v = pref.dhatura;
    Object.defineProperty(pref, "dhatura", {
      configurable: true,
      enumerable: true,
      get() {
        return v;
      },
      set(next) {
        if (next !== v) debugger; // breakpoints when value changes
        v = next;
      }
    });
  })();

Reload or re-run if chameli gets replaced (new array / new objects) — the trap is on the old object reference.

2. Proxy on that object

Same caveat as above; good if many fields change and dhatura is assigned with normal property writes:

  const prefs = globalThis.store.aamras.banana[0].chameli;
  const i = 2;
  const raw = prefs[i];
  prefs[i] = new Proxy(raw, {
    set(t, prop, val) {
      if (prop === "dhatura" && val !== t[prop]) debugger;
      return Reflect.set(t, prop, val);
    }
  });

If something drops [2] and inserts a plain object later, intercept at array level with a Proxy on prefs (set when index === 2), or combine with rerunning after loads.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment