14

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?

Shnick
  • 1,199
  • 1
  • 13
  • 32
  • 8
    It's the [pipeline operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Pipeline_operator), an experimental feature that allows for more readable function chaining. – Lewis Mar 13 '19 at 13:46
  • maybe a duplicate of https://stackoverflow.com/q/54568053/1447675 – Nina Scholz Mar 13 '19 at 13:51
  • @NinaScholz Rather of [Has anyone proposed a Pipe operator for javascript?](https://stackoverflow.com/q/33550393/1048572) – Bergi Mar 13 '19 at 13:55
  • 4
    I don't really think it's a dupe of any of those, but it should be folded into https://stackoverflow.com/q/9549780/476. – deceze Mar 13 '19 at 13:56
  • @deceze Agreed, it's not a duplicate (or else I would already have closed it), I just wanted to suggest that https://stackoverflow.com/q/33550393 has better answers – Bergi Mar 13 '19 at 13:57

3 Answers3

14

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
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
FZs
  • 16,581
  • 13
  • 41
  • 50
3

|> 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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Daniel Turcich
  • 1,764
  • 2
  • 26
  • 48
-2

Check this out! You don't need any new syntax:

const max = [{a: 1, b: 2, c: 3}]
  .map(Object.values)
  .map(_ => Math.max(..._))[0];
console.log(max);

but also, if you already know what map is, the above might help you understand what |> is

Alex028502
  • 3,486
  • 2
  • 23
  • 50