Skip to content

JavaScript pipe operator ( |> ) | Code

  • by

JavaScript pipe operator ( |> ) allows us to pipe a value through a chain of functions. Basic syntax support for the operator looks like this:

The idea behind the pipeline operator was to provide a concise syntax to compose functions in a left-to-right manner, passing the result of one function as the first argument to the next function, and so on. It would make functional programming in JavaScript more elegant and easier to read, especially when dealing with multiple function calls.

expression |> function

Here’s an example of how the pipeline operator would work if it were to be standardized:

// Hypothetical usage of the pipeline operator:
const result = input |> func1 |> func2 |> func3;

In this example, the value of input would be passed as the first argument to func1, the result of func1 would be passed as the first argument to func2, and so on. Finally, the result of func3 would be stored in the result variable.

JavaScript pipe operator ( |> )

Simple example code.

You will need the pipeline operator Babel plugin (or a similar transpiler tool) if you want to run these examples locally.

$ npm install --save-dev @babel/plugin-proposal-pipeline-operator
const double = x => x * 2

const num = 5
const doubled_num = num |> double

console.log(doubled_num)

Output:

JavaScript pipe operator

Source: medium.com

More code

function add(x) {
    return x + 10;
}
  
function subtract(x) {
    return x - 5;
}
  
// Without pipeline operator
let val1 = add(subtract(add(subtract(10))));
console.log(val1);
  
// Using pipeline operator
  
// First 10 is passed as argument to subtract
// function then returned value is passed to
// add function then value we get is passed to
// subtract and then the value we get is again
// passed to add function

let val2 = 10 |> subtract |> add |> subtract |> add;
console.log(val2);

Comment if you have any doubts or suggestions on this JS Operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading