View profile

Reactive vs Imperative Programming

One of my favorite JavaScript interview questions is this: implement a function that converts a Node.
Reactive vs Imperative Programming
By Mastering JavaScript Tutorials • Issue #12 • View online
One of my favorite JavaScript interview questions is this: implement a function that converts a Node.js stream to a promise. A Node.js stream is fundamentally an event emitter with 3 events:
  • data: a new chunk of data is available
  • error: an error occurred
  • end: the stream is finished
The part of this question that I’ve seen a lot of developers struggle with is the concept of reactive programming. Given an event emitter, you cannot control the event emitter. You can only react to what events the event emitter sends you. Many developers struggle because they try to treat an event emitter as an event queue and try to figure out how they can write a while loop to pull events from the event emitter.
Imperative programming means you are responsible for pulling an event off of a queue. Reactive programming means you register a callback and a framework is responsible for calling your callback correctly. In most non-JavaScript languages, imperative programming is the de facto standard. And even in JavaScript, async/await enables imperative programming with asynchronous operations. But realistically, you need both reactive and imperative paradigms: it is easier to write business logic in imperative style, but event handling is much cleaner in reactive style.

This Week's Tutorials
Did you enjoy this issue?
Mastering JavaScript Tutorials

Mastering JavaScript Tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue