CrackFrontendCF
Resources
Practice
CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❤️ by Tushar Khanna

CrackFrontendCF
Resources
Practice

⚡️ Fire on Push: Dispatching Custom Events When an Array Changes in JavaScript

Intercepts array mutations to dispatch custom events when push is called. Enables reactive arrays without frameworks or proxies.

JavaScript arrays are powerful—but they don’t emit events . Want to react when someone es a new item? You’re out of luck... unless you take control. This post shows you how to intercept array mutations and dispatch custom events when is called — all in vanilla JavaScript, no frameworks, no proxies. -- 🧪 The Goal We want to monitor this: And react like this: -- 🛠 Step 1: Custom Array Wrapper -- 🚀 Usage -- 🎯 Why This Works We're overriding on a per-array basis We preserve original functionality via We dispatch a with rich detail -- 🧠 Bonus: Generalizing for Other Methods Want to observe , , or even ? Here’s a sketch: -- 🧬 Alternative: Using Proxies (Advanced) Want a more general-purpose reactive array? Use a . It’s more powerful but less performant: -- 🔚 Conclusion You don’t need Vue or MobX to detect array changes. With just a few lines of JavaScript, you can: Intercept native behavior Dispatch clean, custom events Build observability into data structures This pattern is a foundation for reactive state systems, event-driven logic, or any scenario where "changes should trigger actions." -- Want a React-compatible or Svelte-integrated version? Ask and I'll tailor one. -- <!-quiz-start --Q1: How does the observable array intercept the method? [ ] By using Object.defineProperty [x] By overriding the push method on the specific array instance [ ] By modifying Array.prototype directly [ ] By using a Proxy on all arrays Q2: Why is used in the custom push method? [ ] To make the code shorter [ ] To avoid using the spread operator [x] To call the original push functionality while preserving context [ ] To improve performance Q3: What does the dispatch include in its detail? [ ] Only the array length [ ] The entire array [x] The added items and the new array length [ ] The timestamp of the push <!-quiz-end --
JavaScriptUtilities
➕ Chained Sum (Curried Function)
medium
⏱️ Debounce Function in JavaScript
medium
📋 Deep Clone Implementation
easy
🔄 distinctUntilChanged() Polyfill
easy
📄 Document Comparison (Diff)
easy
📢 Custom EventEmitter Implementation
hard
📦 Flatten Object Implementation
medium
🐫➡️🐍 Converting camelCase to snake_case in JavaScript (Without Regex)
easy
🔄 mapLimit: Controlled Concurrency in JavaScript
medium
⚡️ Fire on Push: Dispatching Custom Events When an Array Changes in JavaScript
medium
🔄 Removing Circular References from Objects
hard
📊 Sampling Function: Execute Once Every N Calls
medium
⏱️ Throttle Function in JavaScript
medium
🔄 undefinedToNull Utility
medium
10 of 14
LibraryJavaScriptUtilities57 of 61

⚡️ Fire on Push: Dispatching Custom Events When an Array Changes in JavaScript

jsutilsmedium

JavaScript arrays are powerful—but they don’t emit events . Want to react when someone .push()es a new item? You’re out of luck... unless you take control.

This post shows you how to intercept array mutations and dispatch custom events when push() is called — all in vanilla JavaScript, no frameworks, no proxies.


🧪 The Goal

We want to monitor this:

myArray.push("newItem");

And react like this:

document.addEventListener("arrayPush", e => {
  console.log("Pushed:", e.detail);
});

🛠 Step 1: Custom Array Wrapper

function createObservableArray(initial = []) {
  const arr = [...initial];

  arr.push = function (...items) {
    const result = Array.prototype.push.apply(this, items);

    const event = new CustomEvent("arrayPush", {
      detail: {
        added: items,
        newLength: this.length
      }
    });

    document.dispatchEvent(event);
    return result;
  };

  return arr;
}

🚀 Usage

const myArray = createObservableArray();

document.addEventListener("arrayPush", (e) => {
  console.log("Array was pushed:", e.detail);
});

myArray.push("alpha");
// logs: { added: ["alpha"], newLength: 1 }

myArray.push("beta", "gamma");
// logs: { added: ["beta", "gamma"], newLength: 3 }

🎯 Why This Works

  • We're overriding push() on a per-array basis
  • We preserve original functionality via Array.prototype.push.apply(...)
  • We dispatch a CustomEvent with rich detail

🧠 Bonus: Generalizing for Other Methods

Want to observe pop, shift, or even splice? Here’s a sketch:

function makeObservable(arr, methods = ["push"]) {
  for (const method of methods) {
    const original = arr[method];
    arr[method] = function (...args) {
      const result = original.apply(this, args);
      document.dispatchEvent(new CustomEvent(`array:${method}`, {
        detail: { args, result, current: [...this] }
      }));
      return result;
    };
  }
  return arr;
}
const list = makeObservable([]);
document.addEventListener("array:push", e => console.log("Pushed", e.detail));
document.addEventListener("array:pop", e => console.log("Popped", e.detail));

list.push("x");
list.pop();

🧬 Alternative: Using Proxies (Advanced)

Want a more general-purpose reactive array? Use a Proxy. It’s more powerful but less performant:

function reactiveArray(arr = []) {
  return new Proxy(arr, {
    get(target, prop) {
      if (prop === "push") {
        return (...items) => {
          const result = Array.prototype.push.apply(target, items);
          document.dispatchEvent(new CustomEvent("arrayPush", {
            detail: { added: items }
          }));
          return result;
        };
      }
      return Reflect.get(target, prop);
    }
  });
}

🔚 Conclusion

You don’t need Vue or MobX to detect array changes. With just a few lines of JavaScript, you can:

  • Intercept native behavior
  • Dispatch clean, custom events
  • Build observability into data structures

This pattern is a foundation for reactive state systems, event-driven logic, or any scenario where "changes should trigger actions."


Want a React-compatible or Svelte-integrated version? Ask and I'll tailor one.


Quick Quiz

Test your understanding with 3 quick questions

Q1How does the observable array intercept the `push` method?
Q2Why is `Array.prototype.push.apply(this, items)` used in the custom push method?
Q3What does the `CustomEvent` dispatch include in its detail?

Continue Reading

CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❤️ by Tushar Khanna