Optional Function Calls In JavaScript
If the below code blocks do not show up properly due to a recent Tumblr change. View them directly at https://obscurejavascript.tumblr.com/
This is useful when using a Publisher/Subscriber pattern or similar. Which is useful for making 2 parts of code communicate when one is loaded before another (e.g. they are both loaded asynchronously). Additionally, those 2 parts of code only need to know about the central element and not each other making it easier to modify one without affecting the other. Firstly, here is a very simple example:
class Mailbox { subscriber = null; register(subscriber) { this.subscriber = subscriber; } publish(message) { if (typeof this.subscriber === 'function') { this.subscriber(message); } } } const mailbox = new Mailbox(); // Keep on publishing messages let number = 1; setInterval(() => { number += 1; mailbox.publish(`Test Message: ${number}`); }, 500) mailbox.register((message) => { console.log('message:', message); }); // message: Test Message: 2 // message: Test Message: 3 // message: Test Message: 4 // and so on...
Notice how the first message was not printed ("Test Message: 1") since the subscriber was not yet available. Which is to simulate when a publisher starts before a subscriber. To handle this a specific function call check needs to be made for subscriber existence. Instead, the original subscriber value could be set to a function. But then it would be hard to determine when a subscriber was set externally to the Mailbox.
Anyways, if optional chaining is supported in your environment, the call can be simplified:
publish(message) { this.subscriber?.(message); }
Optional chaining is currently supported in Chrome, Firefox and a few other environments but not Node.js. Since this is becoming part of the JavaScript standard, it should be in all environments relatively soon.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2020/optionalFunctionCalls.js


















