DEV Community

Cover image for RxJS Operators: map
Steven Boyd-Thompson
Steven Boyd-Thompson

Posted on • Edited on • Originally published at drownedintech.dev

RxJS Operators: map

RxJS is a JavaScript library that enables the creation of asynchronous and event-based programs. The main type is the Observable and a suite of functions and operators are provided to make it easier to work with the data coming through. This series will detail those operators (and a few stand-alone functions) and provide examples of their use.

In this post, we’re going to cover the map operator.

What does it do?

The map operator works the same way as the Array function by the same name. We pass in a function that accepts the current values, performs an operation, and returns the new result. Any operators that come after the map operator will then be using the new value returned from the function.

Example

import { interval, map } from 'rxjs';

interval(1000)
    .pipe(map(x => `Value mapped: ${x}`))
    .subscribe(x => {
        console.log(x);
    });
Enter fullscreen mode Exit fullscreen mode

Here interval is providing sequential integers. The function we pass to the map operator creates a string including that value and returns it. If we run this we will see:

Value mapped: 0
Value mapped: 1
Value mapped: 2
Value mapped: 3
Value mapped: 4
Value mapped: 5
Enter fullscreen mode Exit fullscreen mode

This is a simple example that shows the basic usage of the map operator. More complicated implementations may be used to select specific values of objects that are passed. Or we could apply calculations and return that. The point is, there’s not really a limit to what we can do within the map operator.

There is one caveat. Don’t try and utilise other observables as part of your function. If we want to make use of other observables there are specialised methods to handle this:

  • concatMap
  • exhaustMap
  • mergeMap
  • switchMap

These will be covered in future posts. For now, just stick to basic operations when using map.

The source code for this example is available on GitHub:

Top comments (0)