The operator shown above allows us to pipe a value through a chain of functions. Basic syntax support for the operator looks like this:
expression |> function
To understand why this new operator is useful, it’s worth looking at a real example.
Sidenote: you won’t be able to run this example in any JS engine currently available at the time of posting this article. You will need the pipeline operator babel plugin (or similar transpiler tool) if you want to run these examples locally.
Looking at the above example, you may have come to the conclusion that this operator is pretty useless. In this particular example, you’re absolutely right. We could have just as easily invoked the
double function and passed it our
numconstant. The code below gets us the same output, and it’s easier to understand.
Admittedly, this operator does JUST invoke functions, but it becomes much more useful with longer pipelines.
Here is what that code would look like without the pipeline operator.
Even in a trivial example like this, you can see that the pipeline operator offers better readability. With the pipeline operator, I’m able to read the operations in the order they are executed from top to bottom instead of unraveling an onion of nested function calls in my head. Although the syntax is new, the idea of piping values through multiple operations is not. This functionality exists in many other languages, and shows up inside nearly every JS helper function library like underscore and ramda.
Do we need the pipeline operator?
Being someone who would use it in my own development, I still consider this operator a “nice to have”. I’ve been using this same functionality for a couple of years now with Ramda’s compose and pipe functions, and they don’t cause me any trouble. In the rare case where I absolutely can’t import third-party libraries, I can always write my own piping functionality in a few lines of code.
Is there a downside to adding the operator?
The barrier to entry for self-taught developers is getting higher, and adding new operators for minor convenience is a contributor.
For more information, examples, and updates on the new pipeline operator check out these resources 😀