Search code examples
javascriptnode.jsrxjsarrow-functions

node / javascript () () syntax - how does it work exactly?


Help me understand this code, how output of of (1,2,3) is piped to map( x => x*x) though map( x => x*x) is sequenced 1st in code line and of (1,2,3) is sequenced 2nd

map(x => x*x) (of (1,2,3)).subscribe((value)=> console.log(`value : ${value}`))

same can be written as below, that I understand well, but not above one..

of(1,2,3).pipe(map(x => x*x)).subscribe((value)=> console.log(`value : ${value}`))

FYI, both are correct, and return value 1,4,9

in case you are trying same in editor, include below imports

import {of} from 'rxjs'
import {map} from 'rxjs/operators'

Solution

  • This is actually an example from RxJS documentation, and is explained above:

    A Pipeable Operator is essentially a pure function which takes one Observable as input and generates another Observable as output. Subscribing to the output Observable will also subscribe to the input Observable.

    So what this means is map(x => x*x) returns a kind of function, which takes one Observable as an argument and returns another Observable. Then we invoke that function with (of(1,2,3)) and get our final result, which is, in fact, equal to of(1,2,3).pipe(map(x => x*x))