EN
How to use optional chaining in JavaScript ES2020?
0
points
Why worry about undefined
or null
values when optional chaining can be used?
When something comes from the outside but you are not sure if it is defined or you just want to simplify the logic of your app use this solution. 🔽
Let's start by briefly explaining how the optional chaining operator works.
ES2020 introduced ?.
operator that gives the possibility to avoid testing if an object or property before ?.
notation exists, returning undefined
value if not. The operator can be used with variables, properties, objects, arrays, functions, etc.
The ?.
operator is similar to the .
chaining operator, except that instead of causing an error if a reference is null
or undefined
, the expression returns undefined
value.
📝 Note:
The
?.
optional chaining operator is supported in latest Babel compiler and TypeScript by default.
The syntax looks the following way:
Syntax | Description |
obj?.prop | object property access |
obj?.[expr] | object property access with brackets |
arr?.[index] | array item access by index |
func?.(args) | function calling |
Simple object example:
// ONLINE-RUNNER:browser;
const user = {
name: 'Kate',
age: 25,
};
console.log(user?.name); // Kate
// console.log(user.address.street) // causes error
console.log(user.address?.street) // undefined
Various types examples:
// ONLINE-RUNNER:browser;
// accepted: uninitialised, undefined or null
var obj;
var arr = undefined;
var func = null;
console.log(obj?.items); // undefined
console.log(obj?.['name']); // undefined
console.log(arr?.[10]); // undefined
console.log(func?.('Hello!')); // undefined