Search code examples
javascriptoptional-chaining

What are alternative methods for left side optional chaining in Javascript?


Being that in Javascript optional chaining on the left side of an assignment is not possible, as noted in this question and answer, what are some possible alternative methods to achieve this?

customer.details?.car = { make: 'Toyta' }
  1. I know you can do that with an if

    if (customer.details) {
        customer.details.car = { make: 'Toyota' };
    } else {
        customer.details = { car: { make: 'Toyota' } };
    }
    
  2. I tried with Logical OR || but I'm not sure it's possible and the below is not correct

    customer.(details || {}).car = { make: 'Toyota' };
    
  3. Ternary with spread works (with help from @garrettmills)

    customer.details = customer.details 
        ? { ...customer.details, car: { make: 'Toyota' } }
        : { details: { car: { make: 'Toyota' } } };
    

Are there any other methods?


Solution

  • You're looking for logical nullish assignment, the short form of x = x ?? y:

    (customer.details ??= {}).car = { make: 'Toyota' };
    

    It also works nice with chaining, e.g.

    ((customer.details ??= {}).car ??= {}).make = 'Toyota';