DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Pipeline Operator

The JavaScript Pipeline Operator ( |> ) is used to pipe the value of an expression into a function.

This operator makes chained functions more readable.

This function is called the ( |> ) operator and whatever value is used on the pipeline operator is passed as an argument to the function.

The functions are placed in the order in which they operate on the argument.

๐Ÿ‘‰ Syntax

expression |> function

๐Ÿ‘‰ Using the Pipeline Operator

As the Pipeline Operator is an experimental feature and is currently in the stage 1 proposal, there is no support for currently available browsers. Therefore, is also not included in Node. However, we can use Babel (JavaScript Compiler) to use it.

Steps:

โž– Make sure that Node.js is installed.

โž– Create a directory on our desktop (pipeline-operator), and within that directory create a JavaScript file (main.js).

โž– Navigate to the directory and initialize a package.json file that contains relevant information about the project and its dependencies:

npm init
Enter fullscreen mode Exit fullscreen mode

โž– Install Babel in order to use the operator. A pipeline operator is not currently part of JavaScript language, babel is used to compile the code so that it can be understood by Node.

npm install @babel/cli @babel/core @babel/plugin-proposal-pipeline-operator 
Enter fullscreen mode Exit fullscreen mode

To direct Babel about the compilation of the code properly, a file named .babelrc is created with the following lines:

{
  "plugins": 
  [
      [
          "@babel/plugin-proposal-pipeline-operator",
          {
              "proposal": "minimal"
          }    
      ]
  ]
}
Enter fullscreen mode Exit fullscreen mode

โž– Add a start script to the package.json file which will run babel:

"start": "babel main.js --out-file output.js && node output.js"
Enter fullscreen mode Exit fullscreen mode

โž– Run the code:

npm start
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Example

const step = 5;

function add(x) {
  return x + step;
}

function subtract(x) {
  return x - step;
}

10 |> subtract |> add |> subtract |> add |> console.log;
Enter fullscreen mode Exit fullscreen mode

Stackblitz Demo


I hope you found it useful. Thanks for reading. ๐Ÿ™

Let's get connected! You can find me on:

Top comments (1)

Collapse
 
artydev profile image
artydev

Thank for all your articles