Object.prototype.let

Idea

Instead of…

const phoneNumber =
  data?.customer?.phoneNumber === undefined
    ? undefined
    : formatPhoneNumber(phoneNumber);

I want…

const phoneNumber = data?.customer?.phoneNumber?.let(formatPhoneNumber);

or…

const phoneNumber = data?.customer?.phoneNumber?.let((phoneNumber) =>
  formatPhoneNumber(phoneNumber)
);

Possible Polyfill

Object.prototype.let = function (callbackFn) {
  return callbackFn(this);
}

Notes

The keyword could be something other than let but the idea would be the same: invoke a function passing the object itself as its single argument.

apply and call are already used in other contexts and should probably not be used unless it won't cause confusion.

Hi @mfulton26!

Adding new properties to Object.prototype is unlikely to happen as this could change the behaviour of existing apps.

You might be interested in this idea from @claudiameadows Optional chaining support for the pipeline operator? · Issue #159 · tc39/proposal-pipeline-operator · GitHub. This would let you write:

const phoneNumber = data?.customer?.phoneNumber ?> formatPhoneNumber;

I saw that issue too. Thank you for referencing it. It is similar. The pipeline operator itself is not yet supported by any browsers though.

It is true that this could change the behavior of existing apps but I believe TC39 must be able to move forward with iterating on built-in prototypes and leave existing apps to take care when modifying the prototype of objects that they do not own.

FYI: there are several active proposals at the moment that add to existing prototypes (e.g. tc39/proposal-relative-indexing-method: A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray)).

Adding to existing prototypes is one class of web compatibility risk; adding to Object.prototype is a much, much higher likelihood. Additionally, adding this wouldn't work for anything that inherits from null, like Object.create(null) or import * as ns from 'path', so its usefulness would be limited.

Interesting. So perhaps a language feature like an optional pipeline ?> does make more sense too as it could work with an object with no prototype (like that from Object.create(null)).