Este producto no es compatible con el sitio Datadog seleccionado. ().
Esta página aún no está disponible en español. Estamos trabajando en su traducción.
Si tienes alguna pregunta o comentario sobre nuestro actual proyecto de traducción, no dudes en ponerte en contacto con nosotros.

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

Integraciones sin problemas. Prueba Datadog Code Security