Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

if (obj) obj.someProp ??= 42;
about 4 years ago · Juan Pablo Isaza Denunciar

0

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}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda