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
โ 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
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"
}
]
]
}
โ Add a start script to the package.json file which will run babel:
"start": "babel main.js --out-file output.js && node output.js"
โ Run the code:
npm start
๐ Example
const step = 5;
function add(x) {
return x + step;
}
function subtract(x) {
return x - step;
}
10 |> subtract |> add |> subtract |> add |> console.log;
I hope you found it useful. Thanks for reading. ๐
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyen/
Top comments (1)
Thank for all your articles