javascriptobjectproperties

Optional chaining with assignment


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

Solution

  • 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