Home
← All questions

Fire an event when an element is pushed to an array in JavaScript

MediumPremiumJavaScript

Asked at PharmEasy

JavaScript interview practice: Attach a listener that triggers whenever a new element is pushed onto an array.

Problem

Create a mechanism so that pushing to an array notifies a subscriber with the newly pushed value. Show two approaches: overriding push, and using a Proxy.

function observableArray(arr, onPush) {
  // return an array-like that calls onPush(value) on every push
}
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium