Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!