Before the arrival of JavaScript ES6 (ECMAScript 2015), JavaScript language development happened very slowly. After the ES6 update, new advanced features are added each year. It is also important to note that modern browsers might not support all of the JavaScript features. But with the help of transpilers like Babel, you can use them. Let’s take a look at the new features updated to the JavaScript language in 2020.
Optional chaining is a feature introduced in JavaScript as part of ECMAScript 2020 (ES11) that provides a way to access the properties and methods of an object without the need to explicitly check if each level of the object hierarchy exists. It's represented by the ?.
operator.
Before optional chaining, you typically had to write code like this to safely access nested properties:
if (object && object.property1 && object.property1.property2) {
// Access object.property1.property2 safely
}
With optional chaining, you can simplify this code:
const value = object?.property1?.property2;
Here's how it works:
If
object
isnull
orundefined
, the entire chain short-circuits, and the result isundefined
.If any intermediate property (e.g.,
property1
) isnull
orundefined
, the chain continues, and the result isundefined
.If all properties in the chain exist, the final property (e.g.,
property2
) is accessed, and its value is returned.
Optional chaining is particularly useful when working with APIs or data structures where the presence of properties or elements may not be guaranteed. It helps you write cleaner and more concise code by reducing the need for explicit checks for null or undefined values.