Proposal: Property Accessor Function Shorthand

# sup at aguz.me (4 years ago)

I'd like to hear your feedback on a proposal idea I have and that I couldn't find anything on. Here is what I have so far.

With the rising popularity of functional programming patterns in JavaScript, functions that take an object and return the value of a property are ubiquitous. These are some popular examples:

// filtering by a boolean property
const activeProducts = products.filter(product => product.active);

// mapping
const productNames = products.map(product => product.name);

// sorting, grouping, etc
const sortedProducts = _.sortBy(products, product => product.name);

const { true: activeProducts, false: inactiveProducts } = _.groupBy(
products,
product => product.active
);

This pattern is so common in fact that libraries like lodash (and frameworks) often also accept passing the name of the property as a string:

const sortedProducts = _.sortBy(products, "name");

However, this technique has various problems:

  1. It requires extra code from the library authors. With its typical disadvantages.
  2. It has a potential negative impact on performance.
  3. It is not easily statically analyzable, which makes it hard to type-check, infer, and for tooling to catch typos.

Several languages have solved these problems by introducing some syntactic sugar that simplifies the definition of these functions. My favorite example is Elm's: .property shorthand [1]. If JavaScript supported this syntax, we could write the previous examples as:

const activeProducts = products.filter(.active);
const productNames = products.map(.name);
const sortedProducts = _.sortBy(products, .name);
const { true: activeProducts, false: inactiveProducts } = _.groupBy(products, .active);

This is, in my opinion, nice to read and write. Besides, since this expression simply yields a function, it would not have any of the problems the string approach has.

Combined with the pipeline operator proposal, it would allow code like the following:

orders
  |> filter(.active)
  |> flatMap(.products)
  |> .length

Lastly, engines might be able to optimize this further (or more easily) than normal functions since functions defined this way would be restricted to returning a constant property of the object that is passed to them. They would not be able to have any other expressions or statements in them. Unfortunately, they would not be considered automatically pure because users can implement side effects in property getters or Proxies.

I could not think of any syntax ambiguity this could cause, but I would appreciate your thoughts in this regard. It does look similar to the RHS of a Member Expression, but it would not be ambiguous because the two would not be allowed under the same contexts. The F# community has had an interesting ongoing conversation [2] about the topic, but it is my understanding we would not have these problems in JavaScript since Call Expressions require parenthesis.

[1] elm-lang.org/docs/syntax#records [2] fsharp/fslang-suggestions#506

I am looking forward to hearing your feedback!

Agustín Zubiaga Head of Engineering @ PINATA

# Bob Myers (4 years ago)

This is a great proposal which I hope can attract the support of the powers that be. The arrival of optional chaining seems to indicate a renewed interest in optimizing the way properties are accessed--which after all is a big part of what JS does for a living.

Using .a to denote a function to retrieve the value of the property named a was actually part of an earlier proposal for a number of ways to extend dot notation. I won't link to that proposal since it's obsolete now, but it also allowed

const getFirstName = .name.first;

With optional chaining syntax, this would presumably also be able to be written as .name?.first.

The earlier proposal also suggested extending this notation to arrays, so that

const head = .[0];

In case you are interested, the current version of the proposal for extended dot notation limits itself to accessing multiple properties with the syntax .{a, b}. It can be found at rtm/js-pick-notation.

FWIW, the syntax .propName does appear to be syntactically unambiguous.

-- Bob

# sup at aguz.me (4 years ago)

I’m glad you like the proposal!

Using .a to denote a function to retrieve the value of the property named a was actually part of an earlier proposal for a number of ways to extend dot notation. I won't link to that proposal since it's obsolete now, but it also allowed

const getFirstName = .name.first;

Going multiple levels deep and using optional chaining certainly sounds appealing. However, I'm a little concerned with the ramifications of supporting that syntax.

.name.first

could also mean

((u) => u.name).first

The former is undoubtedly more useful, and it would probably have precedence, but it makes parsing and reading harder. Also, once you support this, it makes it seem like the first dot is a placeholder for the first argument, and then shouldn't the following be allowed too?

// calling functions
const names = products.map(.details.getName());
// or even
const doubled = [1, 2, 3, 4].map(. * 2);

That's interesting, but it goes beyond the goals of this proposal. That being said, I’m more than open to discuss this aspect, if folks think this is how it should be.

The earlier proposal also suggested extending this notation to arrays, so that

const head = .[0];

I would definitely like it support this, though :)

--

Agustín Zubiaga | Head of Engineering @ PINATA

# sup at aguz.me (4 years ago)

To be clear, the . * 2 example is an exaggeration. It’d be logical to restrict it to (Optional)MemberExpressions but my point is that I think what you’re allowed to do with it is not obvious. I think this is why Elm doesn’t support it.

--

Agustín Zubiaga

# Waldemar Horwat (4 years ago)

On 11/24/19 9:17 PM, Bob Myers wrote:

FWIW, the syntax .propName does appear to be syntactically unambiguous.

It conflicts with contextual keywords such as new . target.

 Waldemar
# Michael Luder-Rosefield (4 years ago)

At the cost of adding more code, but giving more power, perhaps what we want is something akin to Kotlin's it keyword: kotlinlang.org/docs/reference/lambdas.html?_ga=2.238822404.500195435.1575368476-1345353619.1575368476#it-implicit-name-of-a-single-parameter

it: implicit name of a single parameter It's very common that a lambda expression has only one parameter. *If the compiler can figure the signature out itself, it is allowed not to declare the only parameter and omit ->. The parameter will be implicitly

declared under the name it:* ints.filter { it > 0 } // this literal is of type '(it: Int) -> Boolean'

What we'd want is something concise and non-ambiguous to fulfill the same role; something that cannot currently be a valid identifier, maybe. This is the point where I start scanning the keyboard for underutilised symbols... I'm thinking the hash symbol would work. To re-use the original example:

const activeProducts = products.filter(#.active);
const productNames = products.map(#.name);
const sortedProducts = _.sortBy(products, #.name);
const { true: activeProducts, false: inactiveProducts } =
_.groupBy(products, #.active);

It makes intuitive sense in 2 ways, I think; # makes you think of the object hash you're extracting a property from, and also is familiar as something's id from CSS selectors.

We could also extend it to represent multiple parameters: # is also aliased as #0, the 2nd parameter is #1, etc.

Further, dynamic properties would work too: `const fooProducts = products.filter(#[foo]); -------------------------- Dammit babies, you've got to be kind.

# Isiah Meadows (4 years ago)

BTW, all this is very much just a special case of this (existing stage

  1. proposal, and is part of why it exists: tc39/proposal-partial-application

I do find it surprising that property access isn't addressed there, but it seems like it was likely just overlooked - it has no mention in the repo, in the open issues, or even in the closed issues or any of the open or closed pull requests.


Isiah Meadows contact at isiahmeadows.com, www.isiahmeadows.com

# Bob Myers (4 years ago)

Can you clarify in what sense you see this as a special case of that proposal? To put it in very simple terms, we would like to do something like array.map(.name).

# sup at aguz.me (4 years ago)

I do find it surprising that property access isn't addressed there, but it seems like it was likely just overlooked - it has no mention in the repo, in the open issues, or even in the closed issues or any of the open or closed pull requests.

Actually, they do seem to address it here as a non-goal: tc39/proposal-partial-application#support-for-receiver-placeholder

If we had that, then we wouldn’t need a specific syntax for property accessors. However, arrow functions are already pretty compact, so I don’t feel a strong desire for this receiver placeholder syntax or something like Kotlin’s it. I know the same logic applies to a property accessor proposal, but accessing properties in JS is extremely common and in my opinion, deserving of a syntax shorthand.

--

Agustín Zubiaga

# Tab Atkins Jr. (4 years ago)

On Sat, Dec 7, 2019 at 2:01 PM <sup at aguz.me> wrote:

I do find it surprising that property access isn't addressed there, but it seems like it was likely just overlooked - it has no mention in the repo, in the open issues, or even in the closed issues or any of the open or closed pull requests.

Actually, they do seem to address it here as a non-goal: tc39/proposal-partial-application#support-for-receiver-placeholder

If we had that, then we wouldn’t need a specific syntax for property accessors. However, arrow functions are already pretty compact, so I don’t feel a strong desire for this receiver placeholder syntax or something like Kotlin’s it. I know the same logic applies to a property accessor proposal, but accessing properties in JS is extremely common and in my opinion, deserving of a syntax shorthand.

Yes, in general, unfortunately, the partial-application proposal doesn't help with partially applying operators (note in their examples that they explicitly use an add() function, since you couldn't use + with it). You'd have to jump to the competing pipeline proposal for that; +>#.foo is the shortest way to spell it there.

I agree that x=>x.foo is a very small syntax tax to pay to create an

accessor function; I haven't found it problematic to do so in my own coding.