optional chaining js code example
Example 1: conditional chaining chrome
const nameLength = db?.user?.name?.length;
const adminOption = db?.user?.validateAdminAndGetPrefs?.().option;
const optionLength = db?.user?.preferences?.[optionName].length;
const userName = usersArray?.[userIndex].name;
Example 2: method chaining in javascript
class Arithmetic {
constructor() {
this.value = 0;
}
sum(...args) {
this.value = args.reduce((sum, current) => sum + current, 0);
return this;
}
add(value) {
this.value = this.value + value;
return this;
}
subtract(value) {
this.value = this.value - value;
return this;
}
average(...args) {
this.value = args.length
? (this.sum(...args).value) / args.length
: undefined;
return this;
}
}
a = new Arithmetic()
a.sum(1, 3, 6)
.subtract(3)
.add(4)
.value
Example 3: optional chain operator
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName);
Example 4: optional chaining
let myMap = new Map();
myMap.set("foo", {name: "baz", desc: "inga"});
let nameBar = myMap.get("bar")?.name;
Example 5: optional chaining
function tryGetFirstElement<T>(arr?: T[]) {
return arr?.[0];
}
Example 6: optional-chaining operator
if (user?.team?.subscription?.invoices) {
}