Babel 7 : Pipeline Operator in Javascript

ntnprdhmm
2 min readAug 29, 2018

--

The Pipeline Operator

Today, functional programming is really popular in Javascript, especially since ECMAScript new features (like map, reduce, filter or arrow functions), and with the use of popular libraries like lodash.

One popular proposal feature for a next ECMAScript version is the pipeline operator:

|>

It already exists in many programming languages, and is very similar to pipes in Bash. This operator provides syntax sugar to chain function calls.
It has many advantages, like make your code easier to read, or eliminate intermediate variables that are sometimes hard to name.

11
|> decrement
|> double
// -> 20

Javascript doesn’t support the pipeline operator yet, but Babel released a plugin that allows you to use it in your code (see more about it here).

Let’s see how to install and use it !

Play with the Babel proposal

Start a new project

mkdir test-pipeline
cd test-pipeline
yarn init -y

Install Babel

yarn add --dev @babel/core @babel/cli @babel/preset-env
yarn add @babel/polyfill

Install the pipeline operator proposal

yarn add --dev @babel/plugin-proposal-pipeline-operator

Create and edit the babel config file at the project’s root

// babel.config.jsmodule.exports = {
presets: ['@babel/env'],
plugins: [
[
"@babel/plugin-proposal-pipeline-operator",
{
proposal:'minimal',
},
],
],
};

We want to use the pipeline operator to write code, and transpile this code into backwards compatible Javascript with Babel. We will write code in a source folder (src), and Babel will transpile our code and put the output into an other folder (dist). Then, we will execute the transpiled code.

Let’s add some scripts to our package.json file to make our life easier !

// package.json...
"scripts": {
"babel": "./node_modules/.bin/babel src --out-dir dist",
"start": "node dist/main"
},
...

Ok, we are good !
Let’s write some code using the pipeline operator :)
Create a script main.js in the source folder and insert these lines of code, that do some simple math using the pipeline operator.

// src/main.jsconst double = x => x * 2;
const increment = x => x + 1;
const n = 5;const result = n
|> double
|> double
|> increment
|> double;
console.log(result);

Now you can transpile this code using Babel and run it.

yarn babel
yarn start
// 42 !

--

--

ntnprdhmm

I like dystopian scenarios, but only in books and movies.