Skip to content
jshacks.dev
Async

The RxJS map Operator Explained With Examples

Learn how the RxJS map operator transforms each emitted value, how it differs from Array map, and how to use it with pipe, objects and errors in RxJS 7.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, npm and TypeScript logos.

The map operator is the first one most people learn in RxJS, and it does what its name promises: it takes each value an observable emits, runs your function on it and emits the result. It is the same idea as Array.prototype.map, applied to values that arrive over time instead of values that already sit in an array. This post covers how map works in RxJS 7 with printed output, the form of the projection function and its index argument, how map handles objects and errors, the difference between map and switchMap, the common mistakes, such as expecting map to wait for a promise, and when to reach for pluck-style shortcuts. It assumes you can read pipe and subscribe code, and the earlier post on RxJS for developers who already know promises covers those.

The basic behavior

JavaScript
import { of } from "rxjs";
import { map } from "rxjs/operators";

of(1, 2, 3)
  .pipe(map((n) => n * 10))
  .subscribe((value) => console.log(value));
Text
10
20
30

of(1, 2, 3) emits three numbers synchronously, then completes. The map operator subscribes to it, applies the function to each value as it arrives and passes the result downstream. The source and the result have the same number of values. map never adds, drops or reorders emissions, so if you need that, you want a different operator, such as filter, take or mergeMap.

Nothing happens until you subscribe

map returns a new observable. Creating it does no work, and the projection function is not called until someone subscribes.

JavaScript
import { of } from "rxjs";
import { map } from "rxjs/operators";

const doubled = of(1, 2).pipe(
  map((n) => {
    console.log("mapping", n);
    return n * 2;
  }),
);

console.log("pipeline created");

doubled.subscribe();
doubled.subscribe();
Text
pipeline created
mapping 1
mapping 2
mapping 1
mapping 2

The function ran four times, two values for each of two subscriptions. This is the laziness that separates observables from arrays, and it means a map function with a side effect, such as logging or a counter, runs once per subscriber. Keep projection functions pure, and use tap for side effects.

The projection function arguments

The function receives the value and a zero-based index of the emission.

JavaScript
import { of } from "rxjs";
import { map } from "rxjs/operators";

of("a", "b", "c")
  .pipe(map((letter, index) => `${index}:${letter}`))
  .subscribe((value) => console.log(value));
Text
0:a
1:b
2:c

The index counts emissions per subscription, and it restarts for each subscriber. It is useful for numbering, and for alternating behavior. Unlike Array.prototype.map, there is no third argument holding the whole collection, because the rest of the values do not exist yet.

Transforming objects

Most real use is reshaping data: extracting a field, renaming, formatting or computing a derived value.

JavaScript
import { of } from "rxjs";
import { map } from "rxjs/operators";

const users = of(
  { id: 1, first: "Ada", last: "Lovelace" },
  { id: 2, first: "Alan", last: "Turing" },
);

users
  .pipe(map(({ id, first, last }) => ({ id, fullName: `${first} ${last}` })))
  .subscribe((user) => console.log(user));
Text
{ id: 1, fullName: 'Ada Lovelace' }
{ id: 2, fullName: 'Alan Turing' }

Return a new object and do not mutate the incoming one. A mutated value is shared with any other subscriber on the same source, and with the original data, which makes bugs that are hard to trace.

Chaining several maps

Each map takes the output of the previous one. Several small maps are easier to read than one large function, and they cost almost nothing.

JavaScript
import { of } from "rxjs";
import { map } from "rxjs/operators";

of("  Hello  ", " RxJS ")
  .pipe(
    map((text) => text.trim()),
    map((text) => text.toLowerCase()),
    map((text) => `${text}!`),
  )
  .subscribe((value) => console.log(value));
Text
hello!
rxjs!

If you find yourself writing five maps in a row for one conceptual step, collapse them into a named function and use a single map(normalize), which is easier to test.

Errors thrown in the projection

If the function throws, the error travels down the error channel, and the observable ends for that subscriber.

JavaScript
import { of } from "rxjs";
import { map, catchError } from "rxjs/operators";

of('{"a": 1}', "not json", '{"a": 3}')
  .pipe(
    map((text) => JSON.parse(text).a),
    catchError((error) => of(`recovered from ${error.name}`)),
  )
  .subscribe({
    next: (value) => console.log("value:", value),
    complete: () => console.log("complete"),
  });
Text
value: 1
value: recovered from SyntaxError
complete

The third string was never processed. After the error, the source subscription was torn down, and catchError replaced the stream with a one-value fallback. If you want to keep going after a bad value, handle the error inside the projection, so the stream does not end.

JavaScript
import { of } from "rxjs";
import { map } from "rxjs/operators";

const safeParse = (text) => {
  try {
    return JSON.parse(text).a;
  } catch {
    return null;
  }
};

of('{"a": 1}', "not json", '{"a": 3}')
  .pipe(map(safeParse))
  .subscribe((value) => console.log(value));
Text
1
null
3

All three values passed through, and the bad one became null. This is the "catch inside" pattern, which matters most in long-lived streams such as an event feed, where one bad item should not kill the whole subscription.

map does not wait for promises

A common mistake is returning a promise or an observable from map.

JavaScript
import { of } from "rxjs";
import { map } from "rxjs/operators";

of(1, 2)
  .pipe(map((id) => Promise.resolve(`user ${id}`)))
  .subscribe((value) => console.log(value));
Text
Promise { 'user 1' }
Promise { 'user 2' }

The output is the promises themselves, because map emits whatever the function returns, without unwrapping it. To flatten, use one of the higher-order operators, which subscribe to the inner observable or promise and emit its values.

JavaScript
import { of } from "rxjs";
import { mergeMap } from "rxjs/operators";

of(1, 2)
  .pipe(mergeMap((id) => Promise.resolve(`user ${id}`)))
  .subscribe((value) => console.log(value));
Text
user 1
user 2

The rule to remember is that if the projection returns a plain value, use map, and if it returns an observable or a promise, use switchMap, mergeMap, concatMap or exhaustMap. Their differences are covered in the posts on switchMap and mergeMap.

OperatorDoes what
map(fn)Replaces each value with fn(value)
mapTo(x)Replaces each value with a constant (deprecated, use map(() => x))
pluck("a", "b")Reads a nested property (deprecated, use map((v) => v.a.b) or optional chaining)
tap(fn)Runs fn for side effects, passes the value through unchanged
filter(fn)Drops values for which fn is falsy
scan(fn, seed)Accumulates, emitting each running result

mapTo and pluck are deprecated in RxJS 7 and removed in RxJS 8, and a plain map covers both.

JavaScript
import { of } from "rxjs";
import { map } from "rxjs/operators";

of({ user: { name: "Ada" } })
  .pipe(map((value) => value.user?.name ?? "unknown"))
  .subscribe(console.log);
Text
Ada

Typing in TypeScript

map infers its output type from the function, so pipelines keep their types.

TypeScript
import { of } from "rxjs";
import { map } from "rxjs/operators";

const lengths = of("a", "bb", "ccc").pipe(map((text) => text.length));
// lengths: Observable<number>

If a projection returns a union, the observable's type is the union, and a following filter with a type guard narrows it again.

When not to use map

Use plain array methods when the data is already an array, since there is no benefit from an observable. Use tap when you want a side effect and not a transformation. And do not use map with a function that performs asynchronous work. That is a job for a higher-order operator.

Choosing a style for projections

There are three habits worth adopting. Give nontrivial projections a name, such as toViewModel or normalizeUser, and pass the name to map, so the pipeline reads like a sentence and the function can be tested without observables. Keep each projection free of side effects and of reads from mutable outside state, since it runs once per subscriber and its result should depend only on its input. And be deliberate about types: a projection that returns different shapes in different branches produces a union type that every later operator has to deal with, so normalize to one shape inside the function.

In team code, map is also the place where unit conversions and formatting belong, close to the data, and not scattered through components. If a value must be displayed as a currency string, convert it in one map near the source, and the rest of the pipeline can treat the amount as a number. That separation makes bugs easy to find, since a wrong value can only have come from a handful of projections.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.