Subtle difference between map and pluck RxJS operators that you should know

Photo by delfi de la Rua on Unsplash

Do you think the following code snippet will give the same result?

Well, the answer is: not really. Let’s take a closer look to see the subtle difference.

How map operator works

According to the official documentation, here’s what map operator does

Applies a given project function to each value emitted by the source Observable, and emits the resulting values as an Observable.

But that’s not the full picture. What if an error in projection function occurs? When I deep dive into the implementation of map operator, here’s what I figured out.

map operator implementation

You can see from the above implementation, if an error occurs in projection function, map will emit an error notification and your output stream will hang on.

How pluck operator works

Here’s what pluck does from the official docs

Maps each source value (an object) to its specified nested property.

When I read this line, there’s a question popping out in my mind, what if the nested property does not exist in object?

And here’s the answer when I consult the source code of pluck operator

pluck calls map under the hood, with a difference

As you can see, pluck operator calls map operator behind the scene, and passes the plucker as projection function. Let's see what does plucker do.

inside plucker function

So, from the above code, we can see that pluck operator will get the nested value from an object based on the property list you provided. For example, you call pluck('employee', 'address', 'houseNumber') , it will try to get the value at object.employee.address.houseNumber, with the main difference is that it ensures null safe.

If there’s no value inside nested object, it will return undefined, and your stream will continue to the next emitted value, rather than throwing an error and stop like map does. And this is the main difference between map and pluck operator.


Let me give you a concrete example to recap. Suppose I have the following input data

source stream

And I have two stream of data

And here’s the visualization of streamWithMap and streamWithPluck accordingly

stream with map
stream with pluck

If I change the streamWithMap like this, the result will be the same as when I use pluck

this will give the same result as pluck


Throughout the article, I have explained in details what’s the main difference between map and pluck operators in RxJS by deep diving into the implementation. I also give an example and marble diagram to illustrate this difference.

I hope you learned something new from the blog. Thanks for reading.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store