Suppose, you've the following code:
if(!!window.containers.filters) {
if(!!window.containers.filters.params) {
xhrData['filters'] = window.containers.filters.params;
}
}
Here, I'm checking if window.container.filters exist or not and then, I'm checking if window.containers.filters.params exist and based on that, I'm doing my operation.
If I check for window.containers.filters.params directly, then there is a possibility that filters might be undefined and hence, an error like cannot find params of undefined might appear.
I want to know if there is any way if you guys can write a better refactored version of this?
Object.assign() can be useful for building up default objects and then cascading overriding values onto it.
Something like this:
let filters = window.containers.filters;
Object.assign(
xhrData,
(filters && filters.params)
? { filters: filters.params }
: null
)
Marco Alka
Software Engineer, Technical Consultant & Mentor
"Better" as in what? Something you might do is
const filters = window.containers.filters; if (filters && filters.params) { xhrData.filters = filters.params; }But imho, that's just personal taste...