Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
30
rated 0 times [  32] [ 2]  / answers: 1 / hits: 23939  / 9 Years ago, fri, july 24, 2015, 12:00:00

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;
}

More From » javascript

 Answers
1

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

[#65689] Thursday, July 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackie

Total Points: 442
Total Questions: 107
Total Answers: 94

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
jackie questions
Sat, Sep 18, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
;