Riga Locks Notes 2021

#TIL |  Optional Chaining on Methods and Indexes

In ECMAScript 2020 the optional chaining operator was introduced into JavaScript. The question mark right behind the property name helps to prevent null reference exceptions:

const foo = { bar: null };

foo.bar.prop // TypeError: Cannot read properties of undefined = NullReferenceException

foo?.bar?.prop // undefined

This works also on methods calls and index access:

foo.doSomething.?()
foo.aList.?[0]

Important: The parentheses for the parameter listing or the index expression must be preceded by a period!

You can interact with this note (applause, criticism, whatever) by mention it in one of your posts, which will be shown here as a Webmention, or by leaving a good old comment with your GitHub account.

Webmentions

No Webmentions yet...

In case your blog software can't send Webmentions, you can use this form to submit me a mention of this note...


Comments