Awesome
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 (7.23.0)
- TypeScript (partially supported in the transform thanks to error recovery)
- V8
- JSC
- SpiderMonkey