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

82
Views
More concise way to set object property where object might be null or undefined

I have a JavaScript errors object that I'm using in a Salesforce Lightning Web Component on a out-of-box table component called a datatable. I won't go into all the details of how it's used, but for the purposes of my question, errors can be null, or it can have a rows property (which itself is an object, used for row-level errors), and also it can have a table property (also an object, used for table-level errors).

Here are some possible values of errors:

errors = null;

errors = {
    rows: {
        ...
    }
}

errors = {
    table: {
        ...
    }
}

errors = {
    rows: {
        ...
    },
    table: {
        ...
    }
}

When setting a table-level error, I don't want to just say errors = { table: {...}} because then I may be overriding some row-level errors. So here's how I'm currently coding it:

if (errors === null) {
    errors = { table: {} };
} else {
    errors.table = {};
}
errors.table.title = 'You must select at least one item to be returned.';

Is there a more concise way of doing this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You don't need an else:

errors = errors || {};
errors.table = errors.table || {};

In modern JavaScript environments, it's better to use ?? (coalescing operator):

errors = errors ?? {};
errors.table = errors.table ?? {};

And it can be even shorter:

errors ??= {};
errors.table ??= {};

In your case there's not much difference, but || performs an old-school "truthy" test on the value, while ?? just checks for null and undefined.

Speaking of that, in most circumstances when comparing to null, I prefer to use == over === because with == both null and undefined are considered the same thing. It's somewhat fragile to explicitly distinguish between the two in most coding situations.

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!