Re:Safe Assignment
by spankalee on Friday September 13, 2024 @01:27PM
(#41533261)
The real safe assignment that I want to see is for optional chaining to be valid in LHS of assignments:
This would not perform the assignment if an optionally chained value was nullish. It downlevels to
Given that the assignment is a SyntaxError now, this should be possible.
[ Parent
| on HN ]
You can avoid the SyntaxError by abusing boolean expressions a bit:
> obj = {}
{}
> obj != null && (obj.bar = 42)
42
> obj
{ bar: 42 }
Not as pretty as your LHS case, but it works.With the length of that you might as well do:
if (obj) obj.bar = 42