The optional chaining operator (
?.) allows us to access deeply nested object properties without having to validate each reference in the nesting chain. In case of a reference being nullish (
undefined) the optional chaining operator will short-circuit, returning
undefined. The optional chaining operator can also be used with function calls, returning
undefined if the given function does not exist.
The resulting code is shorter and simpler, as you can see below:
const data = getDataFromMyAPI(); // Without optional chaining const userName = data && data.user && data.user.name; const userType = data && data.user && data.user.type; data && data.showNotifications && data.showNotifications(); // With optional chaining const userName = data?.user?.name; const userType = data?.user?.type; data.showNotifications?.();
In the same spirit, the nullish coalescing operator (
??) is a logical operator that allows us to check for nullish (
undefined) values, returning the right-hand side operand when the value is non-nullish, otherwise returning the left-hand side operand.
Apart from cleaner code, this operator might spare us some headaches related to falsey values:
const config = getServerConfig(); // Without nullish coalescing const port = config.server.port || 8888; // Oops! This will be true even if we pass it false const wrongkeepAlive = config.server.keepAlive || true; // We'll have to explicitly check for nullish values const keepAlive = (config.server.keepAlive !== null & config.server.keepAlive !== undefined) ? config.server.keepAlive : true; // With nullish coalescing const port = config.server.port ?? 8888; // This works correctly const keepAlive = config.server.keepAlive ?? true;