Stage 1
Classification: Syntactic Change Semantic Change
Human Validated: KW
Title: Optional chaining in assignment LHS
Authors: Nicolò Ribaudo
Champions: Nicolò Ribaudo
Last Presented: July 2023
Stage Upgrades:
Stage 1: 2023-07-16
Stage 2: NA
Stage 2.7: NA
Stage 3: NA
Stage 4: NA
Last Commit: 2024-01-23
Topics: others objects
Keywords: optional chaining assignment object property
GitHub Link: https://github.com/tc39/proposal-optional-chaining-assignment
GitHub Note Link: https://github.com/tc39/notes/blob/HEAD/meetings/2023-07/july-13.md#optional-chaining-in-assignment-lhs-for-stage-1-or-2

Proposal Description:

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