0%

optional chaining

Optional chaining

Why optional chaining

Have you write the following code before?

1
2
3
if (user && user.address && user.address.street) {
console.log(user.address.street);
}

With optional chaining operator, you don’t need so many && to get a deeply nested property.

1
console.log(user?.address?.street);

How to use optional chaining

The optional chaining (?.) operator accesses an object’s property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.

Access object’s property

1
2
3
4
5
6
const person = {
name: 'Philip',
};

console.log(person.info.address); // TypeError: Cannot read property 'address' of undefined.(Because, person does not have property 'info')
console.log(person.info?.address); // undefined

Call a function

1
2
3
4
5
6
7
8
9
10
function doSomething(onContent, onError) {
try {
// Do something with the data
} catch (err) {
// Testing if onError really exists
if (onError) {
onError(err.message);
}
}
}

With optional chaining, you don’t need too check weather onError is defined or not.

1
2
3
4
5
6
7
function doSomething(onContent, onError) {
try {
// Do something with the data
} catch (err) {
onError?.(err.message); // No exception if onError is undefined
}
}

Short circuit

When using optional chaining, if the left operand is null or undefined, the expression will not be evaluated, for instance:

1
2
3
4
5
let i = 0;
const nums = null;
const firstNumber = nums?.[i++];
console.log(x); // 0, since num?. trigger short circuit, [i++] is not evaluated.

?. not work for non-declared root object

Optional chaining can not be used with a non-declared root object, but can be used with a root object that is null or undefined.

1
2
3
console.log(a?.b); // Uncaught ReferenceError: a is not defined
console.log(null?.b); // undefined
console.log(undefined?.b); // undefined

In javascript, not defined and undefined are two different concepts. See undefined vs not defined

Unit test coverage for optional chaining

Reference