Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
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?

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

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';
about 4 years ago · Santiago Gelvez Relatório

0

I prefer:

customer.details = {
    ...(customer.details || {}),
    car: { make: 'toyota' },
}

since it implies that you are "overlaying" details with a new property.

It's worth noting that your example (3) doesn't seem to work quite right. If the customer already has a details field, then the entire customer record will be replaced with { details: { car: ... } }.

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda