Called "optional chaining", it's currently a TC39 proposal in Stage 4. A Babel plugin however is already available in v7.
Example usage:
const obj = {
foo: {
bar: {
baz: 42,
},
},
};
const baz = obj?.foo?.bar?.baz; // 42
const safe = obj?.qux?.baz; // undefined
Answer from Brent L on Stack OverflowCSS instead of using JS ternary operator to check for null/empty values before adding a "%" or prepending a "$"
[AskJS] Nullish Check in conditional
[AskJS] JavaScript operators like or ( || ), and ( && ), null coalescing ( ?? ) makes weak comparasion?
Thoughts on the Null Coalescing (??) operator precedence?
Videos
Called "optional chaining", it's currently a TC39 proposal in Stage 4. A Babel plugin however is already available in v7.
Example usage:
const obj = {
foo: {
bar: {
baz: 42,
},
},
};
const baz = obj?.foo?.bar?.baz; // 42
const safe = obj?.qux?.baz; // undefined
Js logical operators return not true or false, but truly or falsy value itself. For example in expression x && y, if x is falsy, then it will be returned, otherwise y will be returned. So the truth table for operator is correct.
In your case you could use expression customers && customers.orders && customers.orders.Length to get length value or the first falsy one.
Also you can do some magic like ((customers || {}).orders || {}).length
(Personally, I don't like this syntax and possible garbage collection pressure as well)
Or even use maybe monad.
function Option(value) {
this.value = value;
this.hasValue = !!value;
}
Option.prototype.map = function(s) {
return this.hasValue
? new Option(this.value[s])
: this;
}
Option.prototype.valueOrNull = function() {
return this.hasValue ? this.value : null;
}
var length =
new Option(customers)
.map("orders")
.map("length")
.valueOrNull();
It's longer than all the previous approaches, but clearly shows your intentions without any magic behind.