Skip to content

tc39/proposal-optional-chaining-assignment

main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
June 30, 2023 19:26
June 30, 2023 19:26
June 30, 2023 19:26
June 30, 2023 19:26
July 16, 2023 20:28
June 30, 2023 19:47
July 16, 2023 20:28

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 syntax Equivalent ES2023
expr1?.prop = val expr1 == null ? undefined : expr1.prop = val
expr1?.prop += val expr1 == null ? undefined : expr1.prop += val
expr1?.prop ??= val expr1 == null ? undefined : expr1.prop ??= val
expr1?.[key] = val expr1 == null ? undefined : expr1[key] = val
expr1?.foo().prop[key] = val expr1 == null ? undefined : expr1.foo().prop[key] = val

Implementations

  • Babel
  • TypeScript (partially supported in the transform thanks to error recovery)
  • V8
  • JSC
  • SpiderMonkey