C# 6.0 has just been released and has a new nice little feature that I'd really like to use in JavaScript. They're called Null-conditional operators. These use a ?.
or ?[]
syntax.
What these do is essentially allow you to check that the object you've got isn't null
, before trying to access a property. If the object is null
, then you'll get null
as the result of your property access instead.
int? length = customers?.Length;
So here int
can be null, and will take that value if customers
is null. What is even better is that you can chain these:
int? length = customers?.orders?.Length;
I don't believe we can do this in JavaScript, but I'm wondering what's the neatest way of doing something similar. Generally I find chaining if
blocks difficult to read:
var length = null;
if(customers && customers.orders) {
length = customers.orders.length;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…