Worth to know this too in JavaScript — Part 01

Nadun Malinda
Ascentic Technology
3 min readJul 11, 2021

--

This is the first part of the series of small tutorials/articles about some of the cool features in JavaScript which sometimes we don’t use very often but worth knowing. Initially, I planned to include all of them in a single article, but since then things become more comprehensive, I’ve decided to split them into a mini-series. So, enjoy 😎

1) Optional Chaining

Syntax:- ?. (question mark and a period)

Sometimes, you have to access values in an object but you’re not exactly sure about the existence of that property inside that object. In such a case, in any chance that property cannot found inside that object, you’ll end up with an error if you try to access that property. See this example below:-

In order to avoid this kind of errors, you can simply use the Optional Chaining Operator in your code. So it’ll basically avoid causing an error if a reference is nullish (null or undefined). Then the expression short-circuits and returns undefined.

Now let’s see how we can safely escape from a situation like above using the Optional Chaining Operator:-

Now the code will first look for the existence of the address property inside the contact property (also an object). Since it does not exist, code will not execute any further in the line, instead, it just returns undefined. So you can safely avoid additional conditional checks to look for the existence of the address property.

This also works with methods and return undefined if the method does not exist inside the object.

Also can be used to access properties using bracket ([]) instead of using dot (.) notation.

Can be used with object property delete as well.

Optional chaining can be only used with reading and deleting operations, you can’t (and don’t) use it with writing operations. In other words, optional changing has no effect while using the left-hand side of an assignment and cause an error.

Summary:-

  • obj?.prop returns obj.prop if prop exists inside the obj object, otherwise undefined.
  • obj.method?.() calls obj.method() if method() exists inside the obj object, otherwise returns undefined.
  • obj?.[prop] returns obj[prop] if prop exists inside the obj object, otherwise undefined.
  • Still, we should use optional chaining carefully and wisely. Because it’ll not hide programming errors when they occur.
  • Check here for browser compatibility.

Thanks 🙏 for reading this and feel free to share this with your colleagues. If you have any questions, I’d love to answer those 😊

--

--

Nadun Malinda
Ascentic Technology

Diligent software engineer with 6+ years of experience in commercial application development. Passionate about JavaScript, TypeScript, ReactJS, Redux and GCP