Sometimes order is null so orderItems is not found.
Since it's null (not undefined), we can't work around it with defaults (since they only apply to things that are missing or undefined, specifically). But since it's at the top level of res.cartFind, we can work around it with nullish coalescing. Remove the {order: ....} part and move .order to the end, then default it with ?? {}, and destructure that:
const { orderItems = [] } = res.cartFind.order ?? {};
Live Example:
function example(res) {
const { orderItems = [] } = res.cartFind.order ?? {};
console.log(orderItems);
}
console.log("When order is null:");
example({
cartFind: {
order: null,
},
});
console.log("When order is not null:");
example({
cartFind: {
order: {
orderItems: [1, 2, 3],
},
},
});
In comments I think you've asked what if order is there and it has orderItems: null in it. With the above, you'd end up with null, because (again) defaults only get used when something is missing or undefined.
The two things that handle both undefined and null (we call those "nullish" values) are nullish coalescing (which we used above), ??, and optional chaining, ?..
If order may be missing, or it may be present but with orderItems: null in it, you can handle that with a combination of the two:
const orderItems = res.cartFind.order?.orderItems ?? [];
Here's how that works:
- If
res.cartFind.order is null or undefined (or missing,which is effectively undefined), then res.cartFind.order?.orderItems results in undefined (it doesn't throw an error the way it would if there weren't a ? after order). If res.cartFind.order isn't null or undefined (nullish), then we try to get orderItems from it.
- So now
res.cartFind.order?.orderItems has been evaluated and given us either undefined or the value of orderItems (which may be anything). By using thatResultValue ?? [] we're saying "use thatResultValue if it isn't null or undefined, but use [] if it is."
Live Example:
function example(res) {
const orderItems = res.cartFind.order?.orderItems ?? [];
console.log(orderItems);
}
console.log("When order is null:");
example({
cartFind: {
order: null,
},
});
console.log("When order is not null and has a valid orderItems:");
example({
cartFind: {
order: {
orderItems: [1, 2, 3],
},
},
});
console.log("When order is not null but doesn't have orderItems:");
example({
cartFind: {
order: {
},
},
});
console.log("When order is not null and has orderItems but it's null:");
example({
cartFind: {
order: {
orderItems: null,
},
},
});
.as-console-wrapper {
max-height: 100% !important;
}