For AI agents: the complete documentation index is available at /tc39-atlas/en/llms.txt, the full documentation bundle is available at /tc39-atlas/en/llms-full.txt, and this page is available as Markdown at /tc39-atlas/en/proposals/proposal-optional-chaining-assignment.md.
  • English
  • Optional chaining in assignment LHS S1

    Proposal details
    Proposal overview

    The proposal extends optional chaining syntax to the left-hand side of assignment operators, so that a property is assigned only when its base object is neither null nor undefined. It covers simple assignment, compound assignment, and logical assignment operators such as ??=.

    Note

    The README below comes from the upstream repository and may contain outdated stage or status metadata. Use the proposal details above as the current source of truth.

    Optional Chaining Assignment

    Proposal to add support for optional chaining on the left of assignment operators: a?.b = c.

    Status

    • Champion: Nicolò Ribaudo
    • Stage: 1
    • Slides:

    Motivation

    It often happens that you need to assign to a property of an object, but only if that object actually exists.

    The standard way to do it is by guarding the assignment using an if statement:

    if (obj) obj.prop = value;

    The language provides a way to read a property of an object but only if that object actually exists (obj?.prop = value), and developers have to remember that the same syntax is not supported when assigning.

    Use cases

    See this gist for examples of where this feature would be useful in the Babel and TypeScript code bases.

    You can look for examples of where you may use optional chaining in your projects by searching for if \((.*?)\)[\s\n]*\{?[\s\n]*\1\.. This regular expression will have both false positives and false negatives, but it's a potential starting point.

    Description

    This proposal introduces the following syntax:

    New syntaxEquivalent ES2023
    expr1?.prop = valexpr1 == null ? undefined : expr1.prop = val
    expr1?.prop += valexpr1 == null ? undefined : expr1.prop += val
    expr1?.prop ??= valexpr1 == null ? undefined : expr1.prop ??= val
    expr1?.[key] = valexpr1 == null ? undefined : expr1[key] = val
    expr1?.foo().prop[key] = valexpr1 == null ? undefined : expr1.foo().prop[key] = val

    Implementations