() => true) for a while now. Introduced as part of ES6 (The 2015 edition of the ECMAScript spec), They allow developers to create easy anonymous functions that use their parent's scoped
The pipe operator (
|>) offers us the ability to chain consecutive functions by passing the output of each function into the next using the
|> characters. Also referred to as a pipline expression, its use may be familiar to those experienced in terminal usage.
There's no question that in the above example, it's easier to read the version of the code that uses the pipe operator, but why is this being suggested?
The Spec indicates that this addition was inspired by the pipe operator in Hack after the State of JS 2020 survey indicated it was the 4th most frequent answer when asked "What is missing from the language?".
- Nesting - Where you wrap each function call inside of another, with subsequent calls appearing closer to the outside. This is particularly hard to read due to subsequent calls being read prior to earlier functions when read left to right.
- Chaining - Where subsequent functions are appended to previous ones via a
.character. While much easier to read than nesting, chaining can only be used for functions that are methods of the return class/type of the previous function. Unlike piping, it also doesn't support literals, awaited promises, and arithmetic to be mixed in with the function calls.
The pipe operator by comparison is extremely flexible, allowing you to pass any expression into the next, using a placeholder value to indicate where the previous expression's output should be inserted. Although subject to change, in the current version of the documentation, the
% character is used (I'm personally not a fan of this choice given its current use for modulus). This allows for all of the following examples to be valid.
This site uses Webmentions to handle likes, comments and other interactions. To leave a comment, you can reply on Twitter, GitHub, or Reddit. While the site will count likes from any source, only twitter likes are currently displayed in the facepile above.