Object dynamic property with or
T.J. Crowder
tj.crowder at farsightsoftware.com
Thu Jun 15 08:59:13 UTC 2017
FWIW, see
* [`||=` is much needed?](https://esdiscuss.org/topic/is-much-needed)
* [Proposal for a `null` coalescing operator](
https://esdiscuss.org/topic/proposal-for-a-null-coalescing-operator)
I'm sure there were others as well. There was an old strawman for a
"default operator" but the old wiki isn't accessible (right now? anymore?).
I'd love to see `??` (and `??=` for that matter), where the "falsiness" is
defined as the value is `null` or `undefined`, e.g.:
```js
a = b ?? c;
```
is in effect
```js
{
const temp = b;
a = temp === null || temp === undefined ? c : temp;
}
```
IIRC, in previous discussions there were firmly-held convictions for just
`undefined` and for both. In pure JavaScript terms, only considering
`undefined` as the falsy value would make sense, but A) `??` is established
as a `null`-coalescing operator elsewhere (e.g., C#), and B) JavaScript has
to interoperate with typed APIs like the DOM that use `null` to mean
"nothing." Contrived example:
```js
function foo(elm) {
elm ??= document.getElementById("y");
}
foo(document.getElementById("x"));
```
Default arguments don't work for the above because they only default on
`undefined`, not both. And in the previous discussions, people wanted `??`
in non-default-argument situations.
Given this has been kicking around for a long time, is there a will to
consider it if a proper proposal is made?
-- T.J. Crowder
On Thu, Jun 15, 2017 at 8:17 AM, somonek <somonek at gmail.com> wrote:
> Hi everyone,
>
> consider the following example:
>
> const myObj = {
> propertyOne: 'someValue',
> propertyTwo: 'another value',
> };
>
> suppose I have to get a non existing property dynamically with a
> fallback on another one:
>
> let myProp = myObj['propertyTwo'];
> if (myObj['propertyThree']) {
> myProp = myObj['propertyThree'];
> }
>
> wouldn't it be nice to have a quicker way of doing that like this?
>
> const myProp = myObj['propertyThree' || 'propertyTwo'];
> this will return undefined of course but some other operator could be used
> like:
> let myProp = myObj['propertyThree' ?? 'propertyTwo'];
> let myProp = myObj['propertyThree' ?? 'propertyFour' ?? 'propertyTwo'];
>
> any thoughts?
>
> cheers,
> Serghei
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170615/1ebeaa00/attachment.html>
More information about the es-discuss
mailing list