-1

[Disclaimer]

I do not encourage anyone to do prototype modification in anyone's code, specially shared (or meant to play along with other's).
This is bad practice (if not plain evil).
Much like force-pushing (on non-purely-personal repos/branches) in git and such tomfooleries, this is not meant to be done
(SPECIALLY IF YOU FEEL LIKE YOU CAN PULL THIS OFF SAFELY ...)

[Question]

For educational/study/recreational/sheer-curiosity I would like to know if the optional chaining operator

anObject?.aField

is actually delegated to some function that can be found somewhere like let's say

Object.prototype.hereIAmThatsMeImTheChainingOperatorsDelegateFunctionNiceToMeetYou

And that said operator would be accessed/changed/wrapped/altered. (still not for production/professional/shared code but just for laughs and giggles)

Something like :

const originalChainOp = Object.prototype.chainOp;
try {
  Object.prototype.chainOp = function wasItNull() {
    const result = originalChainOp.apply(this, arguments);
    console.log({wasItNullIsh:((this??undefined)===undefined), itWas:this});
    return result;
  };
  [1,[null]]?.[1]?.[0]?.(15)
  /* which would log
   > {"wasItNullIsh":false,"itWas":[1,[null]]}
   > {"wasItNullIsh":false,"itWas":[null]}
   > {"wasItNullIsh":true ,"itWas":null}
   then return undefined
  */
} finally {
  Object.prototype.chainOp = originalChainOp;
}

Much like anyone would be able to do something like

const originalMap = Array.prototype.map;
try {
  Array.prototype.map = function iWillLogForFun() {
    const result = originalMap.apply(this, arguments);
    console.table({
      before: this,
      after: result
    });
    return result;
  };
  [1, 5, 7].map(x => x - 3) /*which in encourage you to try */
} finally {
  Array.prototype.map = originalMap;
}

[What I tried]

I tried to browse the

Object.prototype

to see if anything looked like the golden ticket but nothing did ...

Ar3s
  • 2,237
  • 2
  • 25
  • 47
  • 1
    Have you read the [specification](//tc39.es/ecma262/#sec-optional-chaining-chain-evaluation)? – Sebastian Simon Nov 01 '22 at 22:54
  • Definitely not all of it before you pointed it out (and not even all of it since you did). I've read the [13.3.9 "Optional Chains" section of the specification](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-optional-chains "which you pointed me to") but still don't fully grasp how it would point towards a definitive impossibility to track (fiddle with/alter/toy around) executions of said construct ... – Ar3s Nov 02 '22 at 10:17

1 Answers1

0

I would like to know if the optional chaining operator is actually delegated to some [builtin] function [that c]ould be accessed/changed/wrapped/altered?

No, it's not. It is evaluated directly by the engine.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375