Object Fallback
JavascriptOptional Chaining
Ideal case
Let's say you have a Javascript object defined:
let myBag = {
ItemCount: 3,
Items: [{name:"apple"}, {name:"coin"}, {name:"soap"}],
Price: 1.20,
Weight: 10.3
};
To retrieve information from this, you normally do:
myBag.Items[1].name;
Which would return coin
Bad case
But if your bag was empty:
let myBag = {};
Then myBag.Items would return null. And myBag.Items[1] would throw an error.
Solution
To solve this, you can use optional chaining:
myBag?.Items?.[1]?.name;
Notice the syntax ?. is used for both object keys and object arrays.
Fallback - nullish coalescing operator
Introducing the nullish coalescing operator:
let result = getmyvalue() ?? "fallback";
This operator ?? returns the value unless it is null or undefined.
Fallback - or operator
In a similar way, the OR operator can be used.
let result = getmyvalue() || "fallback";
This operator || returns the first "truthy" value.
So if getmyvalue() returns a false, 0, "" etc then result will use the fallback.
Fallback - and operator
In a reverse way, the AND operator can be used.
let result = getmyvalue() && "fallback";
This operator && returns the first "falsey" value.
So if getmyvalue() returns a true then result will use the fallback.