2

ES16+ offers a nice shorthand obj.someMethod?.() to call someMethod if exists on calling object.

Beeing spoiled with this coding sugar, I would also like to assign a value to property if exists, something like obj?.someProp = 42 (which leads to invalid left-hand assignment).

I would like to do it with any object (mostly dataset of HTMLElements). Any idea how to shorten this?

if(obj?.hasOwnProperty("someProp")) obj.someProp = 42
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • The or `||` operator might come in handy here, Depends on where you're using the value, for example: `let var = obj.someProp || 42` var will evaluate to 42 if `obj.someProp` is null or undefined – jackstride Dec 21 '21 at 11:42

4 Answers4

2

well, you can do something like:

obj && (obj.someProp = 42)

But this will not create the obj for you..

However, even though its not asked, why not just simply destructure though?

obj = {...(obj || {}), someProp: 42}
Mali Naeemi
  • 187
  • 1
  • 10
1

You can use the logical nullish assignment operator. It won't help you with obj being undefined though:

if (obj) obj.someProp ??= 42;
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    Interesting, but it does the exact opposite: assigns the value to `someProp` only if it is nullish (i.e. doesn't exist) in `obj`. – Jan Turoň Apr 19 '23 at 10:58
1

There is not currently any syntactical sugar for this using Javascript

It was raised in the tc39 proposal that brought us optional chaining under the discussion should we include "optional property assignment" a?.b = c, but ultimately not supported.

However, this is supported by CoffeeScript's existential operator which given the following example:

el?.href = "b"

CoffeeScript will compile into the following output:

if (el != null) {
  el.href = "b";
}

Related: Optional chaining on the left side in Javascript

KyleMit
  • 30,350
  • 66
  • 462
  • 664
0

I also find Proxy to be useful in some cases:

    const Accessor = obj => new Proxy(obj, {
        get: (o, prop) => o[prop],
        set: (o, prop, val) => prop in o ? (o[prop]=val) : val
    });

    const obj = { a: 20 };
    const accObj = Accessor(obj);
    accObj.a = 24; // obj.a = accObj.a = 24
    occObj.b = 24; // no effect
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169