Introducing JavaScript's Pipe Operator
In this article, I'm going to show you how to use JavaScript's new pipeline |>
operator.
The pipeline operator is not part of the JavaScript language today, but there is a tc39 proposal to add it. However, we can use Babel in order to use the pipeline operator today. Here's how.
How to set up Babel to use the pipeline operator
Set up a new project.
mkdir pipeline-operator-demo
cd pipeline-operator-demo
npm init -y
Then, install Babel and the pipeline operator plugin.
npm install --save-dev @babel/core@7.20.5 @babel/node@7.20.5 @babel/preset-env@7.20.2 @babel/plugin-proposal-pipeline-operator@7.18.9
Next, create a .bashrc
file to instruct Babel how to resolve the pipeline operator.
{
"presets": ["@babel/preset-env"],
"plugins": [
["@babel/plugin-proposal-pipeline-operator", { "topicToken": "#", "proposal": "hack" }]
]
}
As you can see, we're using the hack
proposal for the pipeline operator.
This is the proposal that is currently being discussed in the tc39 committee.
We then specify the topicToken
to be #
, which we'll explain in a moment.
Create a new file called index.js
and add the following code.
function add(x, y) {
return x + y;
}
function square(x) {
return x * x;
}
function double(x) {
return x * 2;
}
Today, if we want to pipe the result of one function into another, we would do it like so:
function add(x, y) {
return x + y;
}
function square(x) {
return x * x;
}
function double(x) {
return x * 2;
}
const result = double(square(add(1, 2)));
console.log(result);
Execute the program using babel-node index.js
. You should see that the result is 18
.
How to use the pipeline operator
Now, refactor the code to use the pipeline operator like so:
function add(x, y) {
return x + y;
}
function square(x) {
return x * x;
}
function double(x) {
return x * 2;
}
const result = add(1, 2) |> square(#) |> double(#);
console.log(result);
If you're familiar with the pipe |
operator in Unix, JavaScript's pipeline operator |>
works
in a similar way.
- First,
add(1, 2)
is executed. The result is3
. 3
is then piped intosquare(#)
where#
is the placeholder for the result of the previous function. Recall#
is thetopicToken
we defined in the.babelrc
file in the previous section. The result ofsquare(#)
where# = 3
is9
.9
is then piped intodouble(#)
where# = 9
. The result is18
.
We can run the code with babel-node index.js
. You should see that the result is still 18
!
Conclusion
In this article, we learned how to use the pipeline operator in JavaScript, which is currently being discussed in the tc39 committee. We also learned how to set up Babel to transpile the pipeline operator into valid JavaScript.
If you want to see a short video seeing this in action, check out this short YouTube video.
What do you think of the pipeline operator? Do you think it's cleaner than the current way of piping functions? Let me know on Twitter!