The optional chaining operator (?.) allows us to safely access properties and methods of objects when the object holding the property might be null or undefined.
This avoids the need to write multiple conditional checks to ensure each level of the access chain is defined.
Before the introduction of the optional chaining operator in JavaScript, we had to manually check if each property existed before trying to access the next one.
The ?. operator is very useful and greatly simplifies our code (and as you know, simpler code is more readable and maintainable).
Basic Syntax
The basic syntax of the optional chaining operator is as follows:
const result = object?.property;
In this case,
- If
objecthas a defined value, it will accesspropertynormally. - If
objectisnullorundefined,resultwill beundefinedand no error will be thrown.
Let’s look at a practical example to better understand how the optional chaining operator works:
let user = {
name: 'Luis',
address: 'A nice house'
};
let postalCode = user?.address?.postalCode;
let postalCode = user?.product?.barcode;
console.log(postalCode); // Result: '12345'
In this example,
- We access the
addressproperty of theuserobject. - Since this property exists, we will get the value ‘A nice house’.
On the other hand,
- We also access
product.barcode(which doesn’t exist) - However, instead of throwing an exception, we will simply get
undefined.
Multiple Chaining
The optional chaining operator can also be used with multiple chaining. This allows us to create safe “chains”
let result = object?.property1?.subproperty?.othersubproperty;
For example,
const user = {
profile: {
address: {
city: 'Madrid'
}
}
};
const city = user.profile?.address?.city;
console.log(city); // 'Madrid'
If user.profile or user.profile.address were null or undefined, city would be undefined, avoiding an error when trying to access a property of an undefined object.
Usage with Methods
The optional chaining operator can also be used to invoke methods that might not be defined:
const result = object?.method?.();
Here, if object or method are null or undefined, no error will be thrown and result will be undefined. If both are defined, method will be invoked.
For example
const person = {
name: 'Ana',
greet: () => 'Hello'
};
const greeting = person.greet?.();
console.log(greeting); // 'Hello'
If person.greet were null or undefined, it would not try to invoke the method and greeting would be undefined.
Accessing Array Elements
Although less common, the optional chaining operator can also be used to access array elements:
const users = [{ name: 'Carlos' }, null, { name: 'Sofia' }];
const firstName = users[0]?.name;
const secondName = users[1]?.name;
const thirdName = users[2]?.name;
console.log(firstName); // 'Carlos'
console.log(secondName); // undefined
console.log(thirdName); // 'Sofia'
Combination with Nullish Coalescing Operator
The optional chaining operator can be combined with the nullish coalescing operator (??) to provide default values:
const user = {};
const name = user.profile?.name ?? 'Default name';
console.log(name); // 'Default name'
Here, name will be 'Default Name' if user.profile is undefined or null.
