Skip to content

OutputNot attempted

Observer: order of notifications

const subscribers = [];
const subscribe = (fn) => {
subscribers.push(fn);
return () => subscribers.splice(subscribers.indexOf(fn), 1);
};
const notify = (data) => [...subscribers].forEach((fn) => fn(data));
const off1 = subscribe((d) => console.log('User1:', d));
subscribe((d) => console.log('User2:', d));
notify('first');
off1();
notify('second');

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

Subscribers run in subscription order. The unsubscribe function closes over its own listener. Copying the array before iterating protects against listeners that unsubscribe during a notify.