JavaScript Language Design: Dot Notation be Namespace or Object System

By Xah Lee. Date: . Last updated: .

JavaScript language syntax design f().g().h() vs h(g(f()))

am writing a JavaScript lib. My question is, to have method chaining or not. This post is sort of a log of my thought process.

Support of method chaining is popular, used in JQuery, D3.js, or just about any lib:


alternative, is traditional


Now, method chaining is convenient. Because it's a linear syntax, no nesting. Nesting is harder to read and harder to write.

But method chaining syntax in JavaScript brings in a semantic complexity.

it works by having each preceding term returning a object that happens to have the next method as property.

The method chaining in JavaScript:

with function nesting, it's simple. It's just functions. Functions return results. You feed functions one after the other.

Actually, the method chaining way is not necessarily semantically more complex.

true, you cannot chain arbitrary methods. You can chain object + method only when they are designed to be used together. However, it's the same with functions. You cannot chain arbitrary functions that doesn't make sense together, such as string function and a number function.

then, thinking about the issue further…

it's not true now that the chaining function by dot notation is on par with nesting functions.

true, they both needs the return type match the next function's parent-object or input. But, the object-with-property way is not a precise way of types. That is, with function nesting, it works only if a function's output matches the input of next function. So, on the whole, we can roughly say, it depends on data type of the lang, or type checking.

but now with objects, the object is some kinda type, but is not as clear-cut. That is, in most langs, types are a cleanly defined set of things. A value belongs to one of the types, always. But with objects, in most langs, it's not true any value is a specific object. Also, the dot notation is sometimes used as namespace, such as the JavaScript JSON object and JavaScript Math object of JavaScript. [see Object Oriented Programing: is Object Data or Namespace?]


all things considered, the conclusion is that, with function nesting, it's easy to understand, and that the type of an output must match type of next input, is easy to understand. But with dot notation chaining, the way it depends on object+property relationships, is complex to understand.

See also:

Chaning by Composition Function in JavaScript

ok. What else? is it possible to write h(g(f())) without nesting.


See JS: Method Chaining and Function Composition

See also: Concepts and Confusions of Prefix, Infix, Postfix and Lisp Notations

Discussions at Google Plus

Ask me question on patreon