Implementing Optional Chaining for Safer Property Access in JavaScript

Guidelines on using optional chaining to prevent runtime errors when accessing deeply nested properties in JavaScript objects.

0 likes
10 views

Rule Content

{
  "title": "Implementing Optional Chaining for Safer Property Access in JavaScript",
  "description": "Guidelines on using optional chaining to prevent runtime errors when accessing deeply nested properties in JavaScript objects.",
  "category": "JavaScript Cursor Rules",
  "rules": [
    {
      "id": "use-optional-chaining",
      "description": "Use optional chaining (?.) when accessing properties of objects that may be null or undefined to prevent runtime errors.",
      "severity": "warning",
      "examples": {
        "bad": [
          "const streetName = user.address.street.name;"
        ],
        "good": [
          "const streetName = user?.address?.street?.name;"
        ]
      }
    },
    {
      "id": "avoid-overuse-optional-chaining",
      "description": "Avoid overusing optional chaining, as it can mask potential issues by returning undefined silently.",
      "severity": "warning",
      "examples": {
        "bad": [
          "const value = obj?.prop1?.prop2?.prop3?.prop4?.prop5;"
        ],
        "good": [
          "const value = obj?.prop1?.prop2?.prop3;"
        ]
      }
    },
    {
      "id": "combine-optional-chaining-nullish-coalescing",
      "description": "Combine optional chaining with the nullish coalescing operator (??) to provide default values when properties are null or undefined.",
      "severity": "info",
      "examples": {
        "bad": [
          "const username = user?.name || 'Guest';"
        ],
        "good": [
          "const username = user?.name ?? 'Guest';"
        ]
      }
    },
    {
      "id": "avoid-optional-chaining-assignment",
      "description": "Do not use optional chaining on the left-hand side of assignments, as it can lead to unexpected behavior.",
      "severity": "error",
      "examples": {
        "bad": [
          "user?.name = 'John';"
        ],
        "good": [
          "if (user) { user.name = 'John'; }"
        ]
      }
    },
    {
      "id": "ensure-optional-chaining-readability",
      "description": "Ensure that the use of optional chaining does not compromise code readability; avoid chaining too many properties.",
      "severity": "info",
      "examples": {
        "bad": [
          "const value = obj?.a?.b?.c?.d?.e?.f?.g?.h?.i?.j;"
        ],
        "good": [
          "const value = obj?.a?.b?.c?.d;"
        ]
      }
    }
  ]
}