JavaScript Method Chaining is not Postfix Operator (2016)

By Xah Lee. Date: . Last updated: .
  1. in JavaScript, there's method chaining x.f.g. its extremely convenient, widely loved, in ruby too. ♥
  2. however, there's a troublesome aspect, namely, object and properties.
  3. method chaining relies on object properties to work, which is a semantic issue.
  4. in most languages there is no postfix operator.
  5. To chain functions, f must return a object and that object must have next f as property.
  6. then, you use the dot notation for property access, to achieve method chaining.
  7. the problem with this is that we rely on a semantic property for its side effect of syntactic convenience.
  8. if dot notation doesn't exist in JavaScript, then x.f(a).g(b) is written as x[f](a)[g](b). Would you still want to chain?
  9. as a practical example, in JavaScript, if f g are functions and their return value are not objects, you cannot chain them.
  10. to be able to chain arbitrary functions, you need a postfix operator. unix pipe x|f|g, Wolfram Language x//f//g

Note: a related concept is function composition. It has somewhat the same purpose of postfix operator with respect to syntax convenience. Because, it avoids nesting, and lets you write sequential application of functions in a sequential manner.

In lisp language that doesn't use operators, function composition is the natural solution. For example, in Clojure, it's called “threading”. e.g. (-> x f1 f2 f3) is equivalent to (f3 (f2 (f1 x))).

in JavaScript and many other languages, if the language doesn't have postfix notation, one can make-do by defining a pipe function.

Object Oriented Programing Dot Notation, Unix Pipe, Postfix Notation