Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "|>" operator do in JavaScript?

I was reading about JavaScript recently and ran into some syntax which seemed foreign to me:

const max = {a: 1, b: 2, c: 3}
  |> Object.values 
  |> (_ => Math.max(..._))

What exactly does |> mean in such a scenario?

like image 899
Shnick Avatar asked Mar 13 '19 13:03

Shnick


2 Answers

The pipeline operator (|>) calls its second operand (which should be a function) and passes its first operand as an argument to it.

That is,

arg |> func

is equivalent to

func(arg)

Its goal is to make function chaining more readable.


As it is now (in 2021), it's a non-standard and experimental thing created by Mozilla that works only in Firefox by enabling it explicitly.

However, because of the usefulness of this feature, there are two competing proposals in TC39, that would each add a different flavor of this operator to the language.

The exact syntax and semantics is to be determined, but in the simplest cases they will be similar to what's described here.


In Mozilla's variant (and the similar F#-style proposal) the code translated to this case will look like this:

const max = (_ => Math.max(..._))(
  Object.values({a: 1, b: 2, c: 3})
)

console.log(max) //3
  • First, pass {a: 1, b: 2, c: 3} to Object.values
  • Then, pass the result to the anonymous function (_ => Math.max(..._))
  • Finally, assign the output to variable max
like image 190
FZs Avatar answered Oct 23 '22 21:10

FZs


|> is the Pipeline Operator. It's currently an experimental operator - it's not yet or may never become standard for JavaScript. It's currently only supported in FireFox via enabling it explicitly.

As such, it is highly recommended to not use it, except for just messing around with it, given its lack of adoption and its experimental nature.

like image 25
Daniel Turcich Avatar answered Oct 23 '22 21:10

Daniel Turcich