Prefer an optional chain instead of chaining operators

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Metadata

ID: javascript-best-practices/prefer-optional-chain

Language: JavaScript

Severity: Info

Category: Best Practices

Description

The JavaScript optional chaining operator (?.) allows you to read the value of a property located deep within a chain of connected objects without having to validate that each reference in the chain is valid. This operator helps prevent potential runtime errors when dealing with nested objects that may or may not exist.

Without the optional chaining operator, you would need to perform a check at each level of the nested structure. This can result in verbose and complex code, which is harder to read and maintain. The optional chaining operator short-circuits this process, returning undefined if a reference is null or undefined before reaching the end of the chain.

To adhere to this rule, you should use the optional chaining operator (?.) whenever you’re dealing with nested objects where a reference might be null or undefined.

Non-Compliant Code Examples

a && a.b;
a && a['b'];
a && a.b != null;

(a || {}).b;
(a || {})['b'];

!a || !a.b;
!a || !a['b'];

Compliant Code Examples

a?.b;
a?.['b']

!a?.b;
!a?.['b'];
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis