jbyrd
jbyrd

Reputation: 5605

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?

Upvotes: 2

Views: 36

Answers (1)

Pointy
Pointy

Reputation: 413916

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.

Upvotes: 3

Related Questions